diff --git a/java/src/org/openqa/selenium/HasDownloads.java b/java/src/org/openqa/selenium/HasDownloads.java index 2b94b44397bdf..ac2e3aa076f72 100644 --- a/java/src/org/openqa/selenium/HasDownloads.java +++ b/java/src/org/openqa/selenium/HasDownloads.java @@ -95,6 +95,10 @@ public String getName() { return name; } + public boolean hasExtension(String extension) { + return extension.startsWith(".") ? name.endsWith(extension) : name.endsWith('.' + extension); + } + public long getCreationTime() { return creationTime; } diff --git a/java/test/org/openqa/selenium/CookieImplementationTest.java b/java/test/org/openqa/selenium/CookieImplementationTest.java index 61080de0b83a3..b5839ef1d21b1 100644 --- a/java/test/org/openqa/selenium/CookieImplementationTest.java +++ b/java/test/org/openqa/selenium/CookieImplementationTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.openqa.selenium.testing.drivers.Browser.ALL; import static org.openqa.selenium.testing.drivers.Browser.CHROME; @@ -311,9 +311,7 @@ public void testShouldWalkThePathToDeleteACookie() { assertThat(driver.manage().getCookieNamed("rodent")).isNull(); Set cookies = driver.manage().getCookies(); - assertThat(cookies).hasSize(2); - assertThat(cookies).contains(cookie1); - assertThat(cookies).contains(cookie3); + assertThat(cookies).containsExactlyInAnyOrder(cookie1, cookie3); driver.manage().deleteAllCookies(); driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html")); @@ -485,14 +483,22 @@ public void testDeleteNotExistedCookie() { @Test public void testDeleteEmptyNamedCookie() { - assertThrows(IllegalArgumentException.class, () -> driver.manage().deleteCookieNamed("")); - assertThrows(IllegalArgumentException.class, () -> driver.manage().deleteCookieNamed(" ")); + assertThatThrownBy(() -> driver.manage().deleteCookieNamed("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cookie name cannot be empty"); + assertThatThrownBy(() -> driver.manage().deleteCookieNamed(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cookie name cannot be empty"); } @Test public void testGetEmptyNamedCookie() { - assertThrows(IllegalArgumentException.class, () -> driver.manage().getCookieNamed("")); - assertThrows(IllegalArgumentException.class, () -> driver.manage().getCookieNamed(" ")); + assertThatThrownBy(() -> driver.manage().getCookieNamed("")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cookie name cannot be empty"); + assertThatThrownBy(() -> driver.manage().getCookieNamed(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cookie name cannot be empty"); } @Test @@ -554,7 +560,7 @@ private void assertCookieIsPresentWithName(final String key) { String documentCookie = getDocumentCookieOrNull(); if (documentCookie != null) { assertThat(documentCookie) - .as("Cookie was not present with name " + key + ", got: " + documentCookie) + .as(() -> "Cookie was not present with name " + key + ", got: " + documentCookie) .contains(key + "="); } } diff --git a/java/test/org/openqa/selenium/DownloadedFileTest.java b/java/test/org/openqa/selenium/DownloadedFileTest.java new file mode 100644 index 0000000000000..a2fd39999a860 --- /dev/null +++ b/java/test/org/openqa/selenium/DownloadedFileTest.java @@ -0,0 +1,41 @@ +// Licensed to the Software Freedom Conservancy (SFC) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The SFC licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.openqa.selenium; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.openqa.selenium.HasDownloads.DownloadedFile; + +class DownloadedFileTest { + @Test + void hasExtension() { + DownloadedFile file = new DownloadedFile("hello.pdf", 0, 0, 15); + assertThat(file.hasExtension("pdf")).isTrue(); + assertThat(file.hasExtension(".pdf")).isTrue(); + + assertThat(file.hasExtension("df")).isFalse(); + assertThat(file.hasExtension("f")).isFalse(); + assertThat(file.hasExtension("p")).isFalse(); + assertThat(file.hasExtension(".p")).isFalse(); + + assertThat(file.hasExtension(".txt")).isFalse(); + assertThat(file.hasExtension("txt")).isFalse(); + assertThat(file.hasExtension("")).isFalse(); + } +} diff --git a/java/test/org/openqa/selenium/bidi/input/DefaultWheelTest.java b/java/test/org/openqa/selenium/bidi/input/DefaultWheelTest.java index 1ef198571e552..b59123f1de1d0 100644 --- a/java/test/org/openqa/selenium/bidi/input/DefaultWheelTest.java +++ b/java/test/org/openqa/selenium/bidi/input/DefaultWheelTest.java @@ -17,12 +17,9 @@ package org.openqa.selenium.bidi.input; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.openqa.selenium.testing.drivers.Browser.CHROME; -import static org.openqa.selenium.testing.drivers.Browser.EDGE; -import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.openqa.selenium.testing.drivers.Browser.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -65,11 +62,11 @@ void shouldScrollToElement() { appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); WebElement iframe = driver.findElement(By.tagName("iframe")); - assertFalse(inViewport(iframe)); + assertThat(inViewport(iframe)).isFalse(); input.perform("iframe", getBuilder(driver).scrollToElement(iframe).getSequences()); - assertTrue(inViewport(iframe)); + assertThat(inViewport(iframe)).isTrue(); } @Test @@ -88,7 +85,7 @@ void shouldScrollFromElementByGivenAmount() { driver.switchTo().frame(iframe); WebElement checkbox = driver.findElement(By.name("scroll_checkbox")); - assertTrue(inViewport(checkbox)); + assertThat(inViewport(checkbox)).isTrue(); driver.switchTo().window(windowHandle); } @@ -108,26 +105,28 @@ void shouldScrollFromElementByGivenAmountWithOffset() { WebElement iframe = driver.findElement(By.tagName("iframe")); driver.switchTo().frame(iframe); WebElement checkbox = driver.findElement(By.name("scroll_checkbox")); - assertTrue(inViewport(checkbox)); + assertThat(inViewport(checkbox)).isTrue(); } @Test @NotYetImplemented(EDGE) @NotYetImplemented(CHROME) void throwErrorWhenElementOriginIsOutOfViewport() { - assertThrows( - BiDiException.class, - () -> { - driver.get( - appServer.whereIs( - "scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); - WebElement footer = driver.findElement(By.tagName("footer")); - WheelInput.ScrollOrigin scrollOrigin = WheelInput.ScrollOrigin.fromElement(footer, 0, 50); - - input.perform( - windowHandle, - getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).getSequences()); - }); + assertThatThrownBy( + () -> { + driver.get( + appServer.whereIs( + "scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); + WebElement footer = driver.findElement(By.tagName("footer")); + WheelInput.ScrollOrigin scrollOrigin = + WheelInput.ScrollOrigin.fromElement(footer, 0, 50); + + input.perform( + windowHandle, + getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).getSequences()); + }) + .isInstanceOf(BiDiException.class) + .hasMessageContaining("move target out of bounds"); } @NeedsFreshDriver @@ -148,7 +147,7 @@ void shouldScrollFromViewportByGivenAmount() { wait.until(driver -> driver.findElement(By.name("nested_scrolling_frame")).isDisplayed()); - assertTrue(inViewport(footer)); + assertThat(inViewport(footer)).isTrue(); } @NeedsFreshDriver @@ -168,22 +167,24 @@ void shouldScrollFromViewportByGivenAmountFromOrigin() { WebElement iframe = driver.findElement(By.tagName("iframe")); driver.switchTo().frame(iframe); WebElement checkbox = driver.findElement(By.name("scroll_checkbox")); - assertTrue(inViewport(checkbox)); + assertThat(inViewport(checkbox)).isTrue(); driver.switchTo().window(windowHandle); } @Test void throwErrorWhenOriginOffsetIsOutOfViewport() { - assertThrows( - BiDiException.class, - () -> { - driver.get(appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame.html")); - WheelInput.ScrollOrigin scrollOrigin = WheelInput.ScrollOrigin.fromViewport(-10, -10); - - input.perform( - windowHandle, - getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).getSequences()); - }); + assertThatThrownBy( + () -> { + driver.get( + appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame.html")); + WheelInput.ScrollOrigin scrollOrigin = WheelInput.ScrollOrigin.fromViewport(-10, -10); + + input.perform( + windowHandle, + getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).getSequences()); + }) + .isInstanceOf(BiDiException.class) + .hasMessageContaining("move target out of bounds"); } private boolean inViewport(WebElement element) { diff --git a/java/test/org/openqa/selenium/build/Build.java b/java/test/org/openqa/selenium/build/Build.java index 30279f4abcbe3..e9165348554f6 100644 --- a/java/test/org/openqa/selenium/build/Build.java +++ b/java/test/org/openqa/selenium/build/Build.java @@ -16,7 +16,6 @@ // under the License. package org.openqa.selenium.build; -import static org.junit.jupiter.api.Assertions.fail; import static org.openqa.selenium.Platform.WINDOWS; import static org.openqa.selenium.build.DevMode.isInDevMode; @@ -57,7 +56,7 @@ public void go() { executeBuild(builder); } catch (Exception e) { e.printStackTrace(System.err); - fail("Cannot build"); + throw new AssertionError("Cannot build", e); } } @@ -83,7 +82,7 @@ private void executeBuild(ProcessBuilder builder) throws Exception { buildWatcher.start(); int exitValue = process.waitFor(); if (exitValue != 0) { - fail("Unable to build artifacts"); + throw new AssertionError("Unable to build artifacts"); } } diff --git a/java/test/org/openqa/selenium/chrome/ChromeOptionsTest.java b/java/test/org/openqa/selenium/chrome/ChromeOptionsTest.java index f1cf397e41a8c..175024bdcb5c6 100644 --- a/java/test/org/openqa/selenium/chrome/ChromeOptionsTest.java +++ b/java/test/org/openqa/selenium/chrome/ChromeOptionsTest.java @@ -23,7 +23,6 @@ import static org.assertj.core.api.InstanceOfAssertFactories.LIST; import static org.assertj.core.api.InstanceOfAssertFactories.MAP; import static org.assertj.core.api.InstanceOfAssertFactories.STRING; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.openqa.selenium.chromium.ChromiumDriverLogLevel.OFF; import static org.openqa.selenium.chromium.ChromiumDriverLogLevel.SEVERE; import static org.openqa.selenium.remote.CapabilityType.ACCEPT_INSECURE_CERTS; @@ -397,6 +396,6 @@ void shouldBeAbleToMergeAnAndroidOption() { var caps = new MutableCapabilities(); var merged = original.merge(caps); - assertEquals(original.asMap(), merged.asMap()); + assertThat(merged.asMap()).isEqualTo(original.asMap()); } } diff --git a/java/test/org/openqa/selenium/devtools/CdpVersionFinderTest.java b/java/test/org/openqa/selenium/devtools/CdpVersionFinderTest.java index bbebb64fa3e1c..e5918115b3239 100644 --- a/java/test/org/openqa/selenium/devtools/CdpVersionFinderTest.java +++ b/java/test/org/openqa/selenium/devtools/CdpVersionFinderTest.java @@ -76,10 +76,10 @@ void shouldReturnAnExactMatchIfFound() { CdpVersionFinder finder = new CdpVersionFinder(5, ImmutableList.of(v84, v85)); Optional info = finder.match(chrome85); - assertThat(info).isEqualTo(Optional.of(v85)); + assertThat(info).contains(v85); info = finder.match(edge84); - assertThat(info).isEqualTo(Optional.of(v84)); + assertThat(info).contains(v84); } @Test @@ -89,7 +89,7 @@ void shouldReturnThePreviousLowestMatchIfNoExactMatchFoundWithinFuzzFactor() { CdpVersionFinder finder = new CdpVersionFinder(5, ImmutableList.of(v84)); Optional info = finder.match(chrome85); - assertThat(info).isEqualTo(Optional.of(v84)); + assertThat(info).contains(v84); } @Test @@ -112,9 +112,9 @@ void canUseBrowserVersionIfNecessary() { CdpVersionFinder finder = new CdpVersionFinder(5, ImmutableList.of(v84, v85)); Optional info = finder.match(chromeVersion); - assertThat(info).isEqualTo(Optional.of(v85)); + assertThat(info).contains(v85); info = finder.match(edgeVersion); - assertThat(info).isEqualTo(Optional.of(v84)); + assertThat(info).contains(v84); } } diff --git a/java/test/org/openqa/selenium/environment/webserver/AppServerTestBase.java b/java/test/org/openqa/selenium/environment/webserver/AppServerTestBase.java index b174fa2b95700..758194dace09c 100644 --- a/java/test/org/openqa/selenium/environment/webserver/AppServerTestBase.java +++ b/java/test/org/openqa/selenium/environment/webserver/AppServerTestBase.java @@ -17,8 +17,10 @@ package org.openqa.selenium.environment.webserver; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static java.util.stream.StreamSupport.stream; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.By.id; +import static org.openqa.selenium.By.tagName; import static org.openqa.selenium.remote.http.Contents.string; import java.io.File; @@ -26,7 +28,6 @@ import java.net.URL; import java.nio.file.Files; import java.time.Duration; -import java.util.stream.StreamSupport; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -72,29 +73,29 @@ public static void quitDriver() { @Test void hostsStaticPages() { driver.get(server.whereIs("simpleTest.html")); - assertEquals("Hello WebDriver", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Hello WebDriver"); } @Test void servesNumberedPages() { driver.get(server.whereIs("page/1")); - assertEquals("Page1", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Page1"); driver.get(server.whereIs("page/2")); - assertEquals("Page2", driver.getTitle()); + assertThat(driver.getTitle()).isEqualTo("Page2"); } @Test void numberedPagesExcludeQuerystring() { driver.get(server.whereIs("page/1?foo=bar")); - assertEquals("1", driver.findElement(By.id("pageNumber")).getText()); + assertThat(driver.findElement(id("pageNumber")).getText()).isEqualTo("1"); } @Test void redirects() { driver.get(server.whereIs("redirect")); - assertEquals("We Arrive Here", driver.getTitle()); - assertTrue(driver.getCurrentUrl().contains("resultPage")); + assertThat(driver.getTitle()).isEqualTo("We Arrive Here"); + assertThat(driver.getCurrentUrl()).contains("resultPage"); } @Test @@ -103,16 +104,16 @@ void sleeps() { driver.get(server.whereIs("sleep?time=1")); long duration = System.currentTimeMillis() - before; - assertTrue(duration >= 1000); - assertTrue(duration < 1500); - assertEquals("Slept for 1s", driver.findElement(By.tagName("body")).getText()); + assertThat(duration >= 1000).isTrue(); + assertThat(duration < 1500).isTrue(); + assertThat(driver.findElement(tagName("body")).getText()).isEqualTo("Slept for 1s"); } @Test void dealsWithUtf16() { driver.get(server.whereIs("encoding")); String pageText = driver.findElement(By.tagName("body")).getText(); - assertTrue(pageText.contains("\u05E9\u05DC\u05D5\u05DD")); + assertThat(pageText).contains("\u05E9\u05DC\u05D5\u05DD"); } @Test @@ -124,9 +125,10 @@ void manifestHasCorrectMimeType() throws IOException { System.out.printf("Content for %s was %s%n", url, string(response)); - assertTrue( - StreamSupport.stream(response.getHeaders("Content-Type").spliterator(), false) - .anyMatch(header -> header.contains(APPCACHE_MIME_TYPE))); + assertThat( + stream(response.getHeaders("Content-Type").spliterator(), false) + .anyMatch(header -> header.contains(APPCACHE_MIME_TYPE))) + .isTrue(); } @Test diff --git a/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java b/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java index af87a5d01401d..10d83f573d0a0 100644 --- a/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java +++ b/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java @@ -18,9 +18,8 @@ package org.openqa.selenium.federatedcredentialmanagement; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assumptions.assumeThat; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.openqa.selenium.testing.drivers.Browser.CHROME; import java.net.MalformedURLException; @@ -42,15 +41,15 @@ import org.openqa.selenium.support.ui.WebDriverWait; @Disabled("https://issues.chromium.org/u/0/issues/425801332") -class FederatedCredentialManagementTest { +final class FederatedCredentialManagementTest { private HasFederatedCredentialManagement fedcmDriver; private WebDriver localDriver; - InProcessTestEnvironment environment = new InProcessTestEnvironment(true); - AppServer appServer = environment.getAppServer(); + private final InProcessTestEnvironment environment = new InProcessTestEnvironment(true); + private final AppServer appServer = environment.getAppServer(); @BeforeEach - public void setup() { + public void setup() throws MalformedURLException { ChromeOptions options = (ChromeOptions) CHROME.getCapabilities(); options.setAcceptInsecureCerts(true); options.addArguments( @@ -64,14 +63,9 @@ public void setup() { localDriver.get(appServer.whereIsSecure("/fedcm/fedcm_async.html")); } - private int getSecurePort() { + private int getSecurePort() throws MalformedURLException { String urlString = appServer.whereIsSecure("/"); - try { - return new URL(urlString).getPort(); - } catch (MalformedURLException ex) { - // This should not happen. - return 0; - } + return new URL(urlString).getPort(); } @AfterEach @@ -91,7 +85,7 @@ private void waitForDialog() { @Test void testDismissDialog() { fedcmDriver.setDelayEnabled(false); - assertNull(fedcmDriver.getFederatedCredentialManagementDialog()); + assertThat(fedcmDriver.getFederatedCredentialManagementDialog()).isNull(); WebElement triggerButton = localDriver.findElement(By.id("triggerButton")); triggerButton.click(); @@ -106,14 +100,16 @@ void testDismissDialog() { assertThat(dialog.getDialogType()).isEqualTo("AccountChooser"); dialog.cancelDialog(); - // Check that the dialog was indeed closed. Unable to get the dialog type since the dialog was - // closed. - assertThrows(NoAlertPresentException.class, dialog::getDialogType); + // Check that the dialog was indeed closed + assertThatThrownBy(dialog::getDialogType) + .as("Unable to get the dialog type since the dialog was closed") + .isInstanceOf(NoAlertPresentException.class) + .hasMessageStartingWith("no such alert"); } @Test void testSelectAccount() { - assertNull(fedcmDriver.getFederatedCredentialManagementDialog()); + assertThat(fedcmDriver.getFederatedCredentialManagementDialog()).isNull(); WebElement triggerButton = localDriver.findElement(By.id("triggerButton")); triggerButton.click(); @@ -133,7 +129,7 @@ void testSelectAccount() { @Test void testGetAccounts() { - assertNull(fedcmDriver.getFederatedCredentialManagementDialog()); + assertThat(fedcmDriver.getFederatedCredentialManagementDialog()).isNull(); WebElement triggerButton = localDriver.findElement(By.id("triggerButton")); triggerButton.click(); diff --git a/java/test/org/openqa/selenium/firefox/FirefoxDriverBuilderTest.java b/java/test/org/openqa/selenium/firefox/FirefoxDriverBuilderTest.java index 81e93951688df..c275047336de1 100644 --- a/java/test/org/openqa/selenium/firefox/FirefoxDriverBuilderTest.java +++ b/java/test/org/openqa/selenium/firefox/FirefoxDriverBuilderTest.java @@ -19,7 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openqa.selenium.firefox.FirefoxAssumptions.assumeDefaultBrowserLocationUsed; import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; @@ -47,7 +46,7 @@ public void builderGeneratesDefaultFirefoxOptions() { Capabilities capabilities = firefoxDriver.getCapabilities(); assertThat(localDriver.manage().timeouts().getImplicitWaitTimeout()).isEqualTo(Duration.ZERO); - assertTrue((Boolean) capabilities.getCapability("acceptInsecureCerts")); + assertThat((Boolean) capabilities.getCapability("acceptInsecureCerts")).isTrue(); assertThat(capabilities.getCapability("browserName")).isEqualTo("firefox"); } diff --git a/java/test/org/openqa/selenium/grid/config/AnnotatedConfigTest.java b/java/test/org/openqa/selenium/grid/config/AnnotatedConfigTest.java index ebd332e269516..da3c5dbd04f4c 100644 --- a/java/test/org/openqa/selenium/grid/config/AnnotatedConfigTest.java +++ b/java/test/org/openqa/selenium/grid/config/AnnotatedConfigTest.java @@ -17,17 +17,14 @@ package org.openqa.selenium.grid.config; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.beust.jcommander.Parameter; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import org.junit.jupiter.api.Test; @@ -44,7 +41,7 @@ class WithAnnotations { WithAnnotations obj = new WithAnnotations(); Config config = new AnnotatedConfig(obj); - assertEquals(Optional.of("brie"), config.get("cheese", "type")); + assertThat(config.get("cheese", "type")).contains("brie"); } @Test @@ -59,8 +56,8 @@ class WithTypes { } Config config = new AnnotatedConfig(new WithTypes()); - assertEquals(Optional.of(true), config.getBool("types", "bool")); - assertEquals(Optional.of(42), config.getInt("types", "int")); + assertThat(config.getBool("types", "bool")).contains(true); + assertThat(config.getInt("types", "int")).contains(42); } @Test @@ -77,24 +74,23 @@ class WithBadAnnotation { .getAll("the", "collection") .orElseThrow(() -> new AssertionError("No value returned")); - assertEquals(2, values.size()); - assertTrue(values.contains("cheddar")); - assertTrue(values.contains("gouda")); + assertThat(values).containsExactly("cheddar", "gouda"); } @Test void shouldNotAllowMapTypeFieldsToBeAnnotated() { - assertThrows( - ConfigException.class, - () -> { - class WithBadAnnotation { - - @ConfigValue(section = "bad", name = "map", example = "") - private final Map cheeses = ImmutableMap.of("peas", "sausage"); - } - - new AnnotatedConfig(new WithBadAnnotation()); - }); + assertThatThrownBy( + () -> { + class WithBadAnnotation { + + @ConfigValue(section = "bad", name = "map", example = "") + private final Map cheeses = ImmutableMap.of("peas", "sausage"); + } + + new AnnotatedConfig(new WithBadAnnotation()); + }) + .isInstanceOf(ConfigException.class) + .hasMessageStartingWith("Map fields may not be used for configuration"); } @Test @@ -109,7 +105,7 @@ class Child extends Parent {} Config config = new AnnotatedConfig(new Child()); - assertEquals(Optional.of("cheddar"), config.get("cheese", "type")); + assertThat(config.get("cheese", "type")).contains("cheddar"); } @Test @@ -128,7 +124,7 @@ class Child extends Parent { Config config = new AnnotatedConfig(new Child()); - assertEquals(Optional.of("gorgonzola"), config.get("cheese", "type")); + assertThat(config.get("cheese", "type")).contains("gorgonzola"); } @Test @@ -152,11 +148,11 @@ class Defaults { Config config = new AnnotatedConfig(new Defaults()); - assertTrue(config.get("default", "bool").isPresent()); - assertTrue(config.getBool("default", "bool").isPresent()); - assertFalse(config.get("default", "int").isPresent()); - assertFalse(config.getInt("default", "int").isPresent()); - assertFalse(config.get("default", "string").isPresent()); + assertThat(config.get("default", "bool").isPresent()).isTrue(); + assertThat(config.getBool("default", "bool").isPresent()).isTrue(); + assertThat(config.get("default", "int").isPresent()).isFalse(); + assertThat(config.getInt("default", "int").isPresent()).isFalse(); + assertThat(config.get("default", "string").isPresent()).isFalse(); } @Test @@ -178,8 +174,8 @@ class TypesToBeFiltered { Config config = new AnnotatedConfig(new TypesToBeFiltered(), ImmutableSet.of("--string", "--bool"), true); - assertEquals(Optional.of(true), config.getBool("types", "boolean")); - assertEquals(Optional.of("A String"), config.get("types", "string")); - assertEquals(Optional.empty(), config.getInt("types", "integer")); + assertThat(config.getBool("types", "boolean")).contains(true); + assertThat(config.get("types", "string")).contains("A String"); + assertThat(config.getInt("types", "integer")).isEmpty(); } } diff --git a/java/test/org/openqa/selenium/grid/config/ConfigTest.java b/java/test/org/openqa/selenium/grid/config/ConfigTest.java index 91d3be89ddf9f..33a755d42dd56 100644 --- a/java/test/org/openqa/selenium/grid/config/ConfigTest.java +++ b/java/test/org/openqa/selenium/grid/config/ConfigTest.java @@ -17,16 +17,14 @@ package org.openqa.selenium.grid.config; +import static java.lang.System.getProperty; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.util.List; -import java.util.Optional; import org.junit.jupiter.api.Test; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; @@ -40,14 +38,14 @@ void ensureFirstConfigValueIsChosen() { new MapConfig(ImmutableMap.of("section", ImmutableMap.of("option", "foo"))), new MapConfig(ImmutableMap.of("section", ImmutableMap.of("option", "bar")))); - assertEquals("foo", config.get("section", "option").get()); + assertThat(config.get("section", "option").get()).isEqualTo("foo"); } @Test void shouldReturnEmptyIfConfigValueIsMissing() { Config config = new MapConfig(ImmutableMap.of()); - assertFalse(config.get("section", "option").isPresent()); + assertThat(config.get("section", "option").isPresent()).isFalse(); } @Test @@ -57,7 +55,7 @@ void shouldReadSystemProperties() { new MapConfig(ImmutableMap.of()), new ConcatenatingConfig("", '.', System.getProperties())); - assertEquals(System.getProperty("user.home"), config.get("user", "home").get()); + assertThat(config.get("user", "home").get()).isEqualTo(getProperty("user.home")); } @Test @@ -68,9 +66,9 @@ void shouldReturnAllMatchingOptions() { new MapConfig(ImmutableMap.of("section", ImmutableMap.of("cake", "fish"))), new MapConfig(ImmutableMap.of("section", ImmutableMap.of("option", "bar")))); - assertEquals(Optional.empty(), config.getAll("cheese", "brie")); - assertEquals(Optional.of(ImmutableList.of("fish")), config.getAll("section", "cake")); - assertEquals(Optional.of(ImmutableList.of("foo", "bar")), config.getAll("section", "option")); + assertThat(config.getAll("cheese", "brie")).isEmpty(); + assertThat(config.getAll("section", "cake")).contains(ImmutableList.of("fish")); + assertThat(config.getAll("section", "option")).contains(ImmutableList.of("foo", "bar")); } @Test @@ -91,7 +89,7 @@ class Settable { Config config = new AnnotatedConfig(settable); - assertEquals(Optional.of(settable.field), config.getAll("food", "kinds")); + assertThat(config.getAll("food", "kinds")).contains(settable.field); } @Test diff --git a/java/test/org/openqa/selenium/grid/config/JsonConfigTest.java b/java/test/org/openqa/selenium/grid/config/JsonConfigTest.java index 4312866b8fc7b..d59ebeb0351aa 100644 --- a/java/test/org/openqa/selenium/grid/config/JsonConfigTest.java +++ b/java/test/org/openqa/selenium/grid/config/JsonConfigTest.java @@ -33,7 +33,7 @@ void shouldUseATableAsASection() { String raw = "{\"cheeses\": {\"selected\": \"brie\"}}"; Config config = new JsonConfig(new StringReader(raw)); - assertThat(config.get("cheeses", "selected")).isEqualTo(Optional.of("brie")); + assertThat(config.get("cheeses", "selected")).contains("brie"); } @Test @@ -52,7 +52,7 @@ void ensureCanReadListOfStrings() { List expected = Arrays.asList("2", "{\"browserName\": \"chrome\"}"); Optional> content = config.getAll("relay", "configs"); - assertThat(content).isEqualTo(Optional.of(expected)); + assertThat(content).contains(expected); } @Test @@ -79,7 +79,7 @@ void shouldContainConfigFromArrayOfTables() { .replace("`", "\""); Config config = new JsonConfig(new StringReader(raw)); - assertThat(config.get("cheeses", "default")).isEqualTo(Optional.of("manchego")); + assertThat(config.get("cheeses", "default")).contains("manchego"); List expected = Arrays.asList( @@ -123,7 +123,7 @@ void ensureCanReadListOfMaps() { "stereotype={\"browserName\": \"htmlunit\",\"browserVersion\": \"chrome\"}", Config.DELIMITER); Optional> content = config.getAll("node", "driver-configuration"); - assertThat(content).isEqualTo(Optional.of(expected)); + assertThat(content).contains(expected); } @Test diff --git a/java/test/org/openqa/selenium/grid/config/MapConfigTest.java b/java/test/org/openqa/selenium/grid/config/MapConfigTest.java index bef5317b4ab68..c641461eba0af 100644 --- a/java/test/org/openqa/selenium/grid/config/MapConfigTest.java +++ b/java/test/org/openqa/selenium/grid/config/MapConfigTest.java @@ -36,7 +36,7 @@ void shouldUseATableAsASection() { Map raw = new Json().toType(json, MAP_TYPE); Config config = new MapConfig(raw); - assertThat(config.get("cheeses", "selected")).isEqualTo(Optional.of("brie")); + assertThat(config.get("cheeses", "selected")).contains("brie"); } @Test @@ -64,7 +64,7 @@ void shouldContainConfigFromArrayOfTables() { Map raw = new Json().toType(json, MAP_TYPE); Config config = new MapConfig(raw); - assertThat(config.get("cheeses", "default")).isEqualTo(Optional.of("manchego")); + assertThat(config.get("cheeses", "default")).contains("manchego"); List expected = Arrays.asList( @@ -97,7 +97,7 @@ void ensureCanReadListOfStrings() { List expected = Arrays.asList("2", "{\"browserName\": \"chrome\"}"); Optional> content = config.getAll("relay", "configs"); - assertThat(content).isEqualTo(Optional.of(expected)); + assertThat(content).contains(expected); } @Test @@ -130,7 +130,7 @@ void ensureCanReadListOfMaps() { "stereotype={\"browserName\": \"htmlunit\",\"browserVersion\": \"chrome\"}", Config.DELIMITER); Optional> content = config.getAll("node", "driver-configuration"); - assertThat(content).isEqualTo(Optional.of(expected)); + assertThat(content).contains(expected); } @Test diff --git a/java/test/org/openqa/selenium/grid/config/TomlConfigTest.java b/java/test/org/openqa/selenium/grid/config/TomlConfigTest.java index 9eaedae3c258b..55d20f02ae576 100644 --- a/java/test/org/openqa/selenium/grid/config/TomlConfigTest.java +++ b/java/test/org/openqa/selenium/grid/config/TomlConfigTest.java @@ -33,7 +33,7 @@ class TomlConfigTest { void shouldUseATableAsASection() { String raw = "[cheeses]\nselected=\"brie\""; Config config = new TomlConfig(new StringReader(raw)); - assertThat(config.get("cheeses", "selected")).isEqualTo(Optional.of("brie")); + assertThat(config.get("cheeses", "selected")).contains("brie"); } @Test @@ -58,7 +58,7 @@ void shouldContainConfigFromArrayOfTables() { }; Config config = new TomlConfig(new StringReader(String.join("\n", rawConfig))); - assertThat(config.get("cheeses", "default")).isEqualTo(Optional.of("manchego")); + assertThat(config.get("cheeses", "default")).contains("manchego"); List expected = Arrays.asList( @@ -81,7 +81,7 @@ void ensureCanReadListOfStrings() { Config config = new TomlConfig(new StringReader(String.join("\n", rawConfig))); List expected = Arrays.asList("2", "{\"browserName\": \"chrome\"}"); Optional> content = config.getAll("relay", "configs"); - assertThat(content).isEqualTo(Optional.of(expected)); + assertThat(content).contains(expected); } @Test @@ -103,7 +103,7 @@ void ensureCanReadListOfMaps() { "stereotype={\"browserVersion\": \"chrome\",\"browserName\": \"htmlunit\"}", Config.DELIMITER); Optional> content = config.getAll("node", "driver-configuration"); - assertThat(content).isEqualTo(Optional.of(expected)); + assertThat(content).contains(expected); } @Test diff --git a/java/test/org/openqa/selenium/grid/distributor/AddingNodesTest.java b/java/test/org/openqa/selenium/grid/distributor/AddingNodesTest.java index 3df9bd79c22a1..562d5aac86b94 100644 --- a/java/test/org/openqa/selenium/grid/distributor/AddingNodesTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/AddingNodesTest.java @@ -18,7 +18,8 @@ package org.openqa.selenium.grid.distributor; import static com.google.common.collect.Iterables.getOnlyElement; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static java.time.Duration.ofSeconds; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.grid.data.Availability.UP; import static org.openqa.selenium.remote.Dialect.W3C; @@ -30,31 +31,14 @@ import java.net.URL; import java.time.Duration; import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.openqa.selenium.Capabilities; -import org.openqa.selenium.ImmutableCapabilities; -import org.openqa.selenium.NoSuchSessionException; -import org.openqa.selenium.SessionNotCreatedException; -import org.openqa.selenium.WebDriverException; +import org.openqa.selenium.*; import org.openqa.selenium.events.EventBus; import org.openqa.selenium.events.local.GuavaEventBus; -import org.openqa.selenium.grid.data.CreateSessionRequest; -import org.openqa.selenium.grid.data.CreateSessionResponse; -import org.openqa.selenium.grid.data.DefaultSlotMatcher; -import org.openqa.selenium.grid.data.NodeId; -import org.openqa.selenium.grid.data.NodeStatus; -import org.openqa.selenium.grid.data.NodeStatusEvent; -import org.openqa.selenium.grid.data.Session; -import org.openqa.selenium.grid.data.SessionClosedEvent; -import org.openqa.selenium.grid.data.Slot; -import org.openqa.selenium.grid.data.SlotId; +import org.openqa.selenium.grid.data.*; import org.openqa.selenium.grid.distributor.local.LocalDistributor; import org.openqa.selenium.grid.distributor.remote.RemoteDistributor; import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector; @@ -155,7 +139,7 @@ void shouldBeAbleToRegisterALocalNode() throws URISyntaxException { wait.until(obj -> distributor.getStatus().hasCapacity()); NodeStatus status = getOnlyElement(distributor.getStatus().getNodes()); - assertEquals(1, getStereotypes(status).get(CAPS)); + assertThat(getStereotypes(status).get(CAPS)).isEqualTo(1); } @Test @@ -196,8 +180,8 @@ void shouldBeAbleToRegisterACustomNode() throws URISyntaxException { wait.until(obj -> distributor.getStatus().hasCapacity()); NodeStatus status = getOnlyElement(distributor.getStatus().getNodes()); - assertEquals(1, getStereotypes(status).get(CAPS)); - assertEquals(Duration.ofSeconds(300), status.getSessionTimeout()); + assertThat(getStereotypes(status).get(CAPS)).isEqualTo(1); + assertThat(status.getSessionTimeout()).isEqualTo(ofSeconds(300)); } } @@ -237,7 +221,7 @@ void shouldBeAbleToRegisterNodesByListeningForEvents() throws URISyntaxException wait.until(obj -> distributor.getStatus().hasCapacity()); NodeStatus status = getOnlyElement(distributor.getStatus().getNodes()); - assertEquals(1, getStereotypes(status).get(CAPS)); + assertThat(getStereotypes(status).get(CAPS)).isEqualTo(1); } } @@ -289,7 +273,7 @@ void shouldKeepOnlyOneNodeWhenTwoRegistrationsHaveTheSameUriByListeningForEvents Set nodes = distributor.getStatus().getNodes(); - assertEquals(1, nodes.size()); + assertThat(nodes).hasSize(1); } } @@ -331,7 +315,7 @@ void distributorShouldUpdateStateOfExistingNodeWhenNodePublishesStateChange() wait.until(obj -> distributor.getStatus().hasCapacity()); NodeStatus nodeStatus = getOnlyElement(distributor.getStatus().getNodes()); - assertEquals(1, getStereotypes(nodeStatus).get(CAPS)); + assertThat(getStereotypes(nodeStatus).get(CAPS)).isEqualTo(1); // Craft a status that makes it look like the node is busy, and post it on the bus. NodeStatus status = node.getStatus(); diff --git a/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java b/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java index 166799e5ab9df..e86a271c2b08a 100644 --- a/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java @@ -18,7 +18,6 @@ package org.openqa.selenium.grid.distributor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.time.Instant; @@ -27,11 +26,7 @@ import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.openqa.selenium.SessionNotCreatedException; -import org.openqa.selenium.grid.data.CreateSessionResponse; -import org.openqa.selenium.grid.data.DefaultSlotMatcher; -import org.openqa.selenium.grid.data.NodeDrainComplete; -import org.openqa.selenium.grid.data.NodeStatus; -import org.openqa.selenium.grid.data.Session; +import org.openqa.selenium.grid.data.*; import org.openqa.selenium.grid.distributor.local.LocalDistributor; import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector; import org.openqa.selenium.grid.node.local.LocalNode; @@ -269,7 +264,7 @@ void drainingNodeDoesNotAcceptNewSessions() { local.add(node); local.drain(node.getId()); - assertTrue(node.isDraining()); + assertThat(node.isDraining()).isTrue(); Either result = local.newSession(createRequest(caps)); diff --git a/java/test/org/openqa/selenium/grid/distributor/SessionSchedulingTest.java b/java/test/org/openqa/selenium/grid/distributor/SessionSchedulingTest.java index 58f1924b83b88..2af8579e8d863 100644 --- a/java/test/org/openqa/selenium/grid/distributor/SessionSchedulingTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/SessionSchedulingTest.java @@ -18,7 +18,6 @@ package org.openqa.selenium.grid.distributor; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openqa.selenium.grid.data.Availability.UP; import java.net.URI; @@ -33,11 +32,7 @@ import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.SessionNotCreatedException; -import org.openqa.selenium.grid.data.CreateSessionResponse; -import org.openqa.selenium.grid.data.DefaultSlotMatcher; -import org.openqa.selenium.grid.data.NodeStatus; -import org.openqa.selenium.grid.data.Session; -import org.openqa.selenium.grid.data.Slot; +import org.openqa.selenium.grid.data.*; import org.openqa.selenium.grid.distributor.local.LocalDistributor; import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector; import org.openqa.selenium.grid.node.Node; @@ -322,7 +317,7 @@ void shouldPrioritizeHostsWithTheMostSlotsAvailableForASessionType() { boolean inChromeNodes = chromeNodes.stream().anyMatch(node -> node.getUri().equals(chromeSession.getUri())); // This could be either, or, or both - assertTrue(inFirefoxNodes || inChromeNodes); + assertThat(inFirefoxNodes || inChromeNodes).isTrue(); } // The Chrome Nodes should be full at this point, but Firefox isn't... so send an Edge session @@ -331,7 +326,8 @@ void shouldPrioritizeHostsWithTheMostSlotsAvailableForASessionType() { local.newSession(createRequest(edge)); assertThatEither(edgeResult).isRight(); Session edgeSession = edgeResult.right().getSession(); - assertTrue(edgeNodes.stream().anyMatch(node -> node.getUri().equals(edgeSession.getUri()))); + assertThat(edgeNodes.stream().anyMatch(node -> node.getUri().equals(edgeSession.getUri()))) + .isTrue(); } private Set createNodeSet( diff --git a/java/test/org/openqa/selenium/grid/distributor/local/LocalDistributorTest.java b/java/test/org/openqa/selenium/grid/distributor/local/LocalDistributorTest.java index 569e85aa19f06..22253bdbf1cb6 100644 --- a/java/test/org/openqa/selenium/grid/distributor/local/LocalDistributorTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/local/LocalDistributorTest.java @@ -249,7 +249,7 @@ private VerifyingHandler(SessionId id, Capabilities capabilities) { @Override public HttpResponse execute(HttpRequest req) { Optional id = HttpSessionId.getSessionId(req.getUri()).map(SessionId::new); - assertThat(id).isEqualTo(Optional.of(getId())); + assertThat(id).contains(getId()); return new HttpResponse(); } } diff --git a/java/test/org/openqa/selenium/grid/gridui/OverallGridTest.java b/java/test/org/openqa/selenium/grid/gridui/OverallGridTest.java index b508370e27b20..920dbf5149776 100644 --- a/java/test/org/openqa/selenium/grid/gridui/OverallGridTest.java +++ b/java/test/org/openqa/selenium/grid/gridui/OverallGridTest.java @@ -17,13 +17,11 @@ package org.openqa.selenium.grid.gridui; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.grid.gridui.Urls.whereIs; import static org.openqa.selenium.json.Json.MAP_TYPE; import static org.openqa.selenium.remote.http.HttpMethod.GET; -import static org.openqa.selenium.support.ui.ExpectedConditions.textToBe; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfAllElementsLocatedBy; -import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; +import static org.openqa.selenium.support.ui.ExpectedConditions.*; import static org.openqa.selenium.testing.Safely.safelyCall; import com.google.common.collect.ImmutableMap; @@ -74,7 +72,7 @@ void shouldReportConcurrencyZeroPercentWhenGridIsStartedWithoutLoad() { wait.until( visibilityOfElementLocated(By.cssSelector("div[data-testid='concurrency-usage']"))); - assertEquals("0%", concurrency.getText()); + assertThat(concurrency.getText()).isEqualTo("0%"); } @Test @@ -85,7 +83,7 @@ void shouldShowOneNodeRegistered() { wait.until( visibilityOfAllElementsLocatedBy(By.cssSelector("button[data-testid*='node-info-']"))); - assertEquals(1, nodeInfoIcons.size()); + assertThat(nodeInfoIcons).hasSize(1); } @Test diff --git a/java/test/org/openqa/selenium/grid/node/ForwardWebDriverCommandTest.java b/java/test/org/openqa/selenium/grid/node/ForwardWebDriverCommandTest.java index e52f5d7d45e77..2606efc81f8ff 100644 --- a/java/test/org/openqa/selenium/grid/node/ForwardWebDriverCommandTest.java +++ b/java/test/org/openqa/selenium/grid/node/ForwardWebDriverCommandTest.java @@ -18,8 +18,9 @@ package org.openqa.selenium.grid.node; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.openqa.selenium.remote.http.Contents.asJson; import java.util.Map; @@ -55,7 +56,7 @@ void testExecuteWithValidSessionOwner() { when(mockNode.executeWebDriverCommand(mockRequest)).thenReturn(expectedResponse); HttpResponse actualResponse = command.execute(mockRequest); - assertEquals(expectedResponse, actualResponse); + assertThat(actualResponse).isEqualTo(expectedResponse); } @Test @@ -81,7 +82,7 @@ void testExecuteWithInvalidSessionOwner() { "Cannot find session with id: " + sessionId, "stacktrace", "")))); - assertEquals(expectResponse.getStatus(), actualResponse.getStatus()); - assertEquals(expectResponse.getContentEncoding(), actualResponse.getContentEncoding()); + assertThat(actualResponse.getStatus()).isEqualTo(expectResponse.getStatus()); + assertThat(actualResponse.getContentEncoding()).isEqualTo(expectResponse.getContentEncoding()); } } diff --git a/java/test/org/openqa/selenium/grid/node/NodeTest.java b/java/test/org/openqa/selenium/grid/node/NodeTest.java index c8db57dccf006..3e355671f49cc 100644 --- a/java/test/org/openqa/selenium/grid/node/NodeTest.java +++ b/java/test/org/openqa/selenium/grid/node/NodeTest.java @@ -691,7 +691,7 @@ void canDeleteFileDownloads() throws IOException { HttpResponse deleteResponse = node.execute(deleteRequest); assertThat(deleteResponse.isSuccessful()).isTrue(); - assertThat(listFileDownloads(session.getId()).isEmpty()).isTrue(); + assertThat(listFileDownloads(session.getId())).isEmpty(); } finally { node.stop(session.getId()); } diff --git a/java/test/org/openqa/selenium/grid/node/config/NodeOptionsTest.java b/java/test/org/openqa/selenium/grid/node/config/NodeOptionsTest.java index d752011e820c9..7f949d7831b5e 100644 --- a/java/test/org/openqa/selenium/grid/node/config/NodeOptionsTest.java +++ b/java/test/org/openqa/selenium/grid/node/config/NodeOptionsTest.java @@ -17,6 +17,7 @@ package org.openqa.selenium.grid.node.config; +import static java.net.URI.create; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.singletonMap; @@ -30,7 +31,6 @@ import com.google.common.collect.ImmutableMap; import java.io.StringReader; -import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -655,8 +655,7 @@ void settingTheHubFlagSetsTheGridUrlAndEventBusFlags() { Config config = new TomlConfig(new StringReader(String.join("\n", rawConfig))); NodeOptions nodeOptions = new NodeOptions(config); - assertThat(nodeOptions.getPublicGridUri()) - .isEqualTo(Optional.of(URI.create("http://cheese.com:4444"))); + assertThat(nodeOptions.getPublicGridUri()).contains(create("http://cheese.com:4444")); } @Test @@ -669,8 +668,7 @@ void settingTheHubWithDefaultValueSetsTheGridUrlToTheNonLoopbackAddress() { String nonLoopbackAddress = new NetworkUtils().getNonLoopbackAddressOfThisMachine(); String nonLoopbackAddressUrl = String.format("http://%s:4444", nonLoopbackAddress); NodeOptions nodeOptions = new NodeOptions(config); - assertThat(nodeOptions.getPublicGridUri()) - .isEqualTo(Optional.of(URI.create(nonLoopbackAddressUrl))); + assertThat(nodeOptions.getPublicGridUri()).contains(create(nonLoopbackAddressUrl)); } @Test diff --git a/java/test/org/openqa/selenium/grid/node/local/LocalNodeTest.java b/java/test/org/openqa/selenium/grid/node/local/LocalNodeTest.java index 640a3318c8aaf..a6bb0676b92d0 100644 --- a/java/test/org/openqa/selenium/grid/node/local/LocalNodeTest.java +++ b/java/test/org/openqa/selenium/grid/node/local/LocalNodeTest.java @@ -202,7 +202,7 @@ private VerifyingHandler(SessionId id, Capabilities capabilities) { @Override public HttpResponse execute(HttpRequest req) { Optional id = HttpSessionId.getSessionId(req.getUri()).map(SessionId::new); - assertThat(id).isEqualTo(Optional.of(getId())); + assertThat(id).contains(getId()); return new HttpResponse(); } } diff --git a/java/test/org/openqa/selenium/grid/node/relay/RelaySessionFactoryTest.java b/java/test/org/openqa/selenium/grid/node/relay/RelaySessionFactoryTest.java index 6b2fd235abdee..7ee268d853ddb 100644 --- a/java/test/org/openqa/selenium/grid/node/relay/RelaySessionFactoryTest.java +++ b/java/test/org/openqa/selenium/grid/node/relay/RelaySessionFactoryTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.grid.node.relay; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; @@ -64,9 +64,9 @@ public void testFilterRelayCapabilities() { capabilitiesWithBundleId = factory.filterRelayCapabilities(capabilitiesWithBundleId); capabilitiesWithoutApp = factory.filterRelayCapabilities(capabilitiesWithoutApp); - assertEquals(null, capabilitiesWithApp.getCapability("browserName")); - assertEquals(null, capabilitiesWithAppPackage.getCapability("browserName")); - assertEquals(null, capabilitiesWithBundleId.getCapability("browserName")); - assertEquals("chrome", capabilitiesWithoutApp.getCapability("browserName")); + assertThat(capabilitiesWithApp.getCapability("browserName")).isEqualTo(null); + assertThat(capabilitiesWithAppPackage.getCapability("browserName")).isEqualTo(null); + assertThat(capabilitiesWithBundleId.getCapability("browserName")).isEqualTo(null); + assertThat(capabilitiesWithoutApp.getCapability("browserName")).isEqualTo("chrome"); } } diff --git a/java/test/org/openqa/selenium/grid/router/DistributedTest.java b/java/test/org/openqa/selenium/grid/router/DistributedTest.java index 46eb746d48b77..25f18396dd4b3 100644 --- a/java/test/org/openqa/selenium/grid/router/DistributedTest.java +++ b/java/test/org/openqa/selenium/grid/router/DistributedTest.java @@ -19,6 +19,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.StringReader; import java.time.Duration; @@ -27,7 +28,6 @@ import java.util.Map; import java.util.Objects; 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.Capabilities; @@ -46,13 +46,7 @@ import org.openqa.selenium.json.JsonInput; import org.openqa.selenium.netty.server.NettyServer; import org.openqa.selenium.remote.RemoteWebDriver; -import org.openqa.selenium.remote.http.ClientConfig; -import org.openqa.selenium.remote.http.ConnectionFailedException; -import org.openqa.selenium.remote.http.Contents; -import org.openqa.selenium.remote.http.HttpClient; -import org.openqa.selenium.remote.http.HttpMethod; -import org.openqa.selenium.remote.http.HttpRequest; -import org.openqa.selenium.remote.http.HttpResponse; +import org.openqa.selenium.remote.http.*; import org.openqa.selenium.testing.Safely; import org.openqa.selenium.testing.TearDownFixture; import org.openqa.selenium.testing.drivers.Browser; @@ -131,9 +125,7 @@ void clientTimeoutDoesNotLeakARunningBrowser() throws Exception { try { // provoke the client to run into a http timeout - SessionNotCreatedException nce = - Assertions.assertThrows( - SessionNotCreatedException.class, + assertThatThrownBy( () -> RemoteWebDriver.builder() .oneOf(browser.getCapabilities()) @@ -141,9 +133,9 @@ void clientTimeoutDoesNotLeakARunningBrowser() throws Exception { ClientConfig.defaultConfig() .baseUrl(server.getUrl()) .readTimeout(Duration.ofMillis(600))) - .build()); - - assertThat(nce.getMessage()).contains("TimeoutException"); + .build()) + .isInstanceOf(SessionNotCreatedException.class) + .hasMessageContaining("TimeoutException"); // ensure the grid has some time to start the browser and shutdown the browser Thread.sleep(Duration.ofNanos((end - start) * 3).toMillis()); @@ -191,7 +183,7 @@ void clientTimeoutDoesNotLeakARunningBrowser() throws Exception { } } - Assertions.assertEquals(1, sessionCount); + assertThat(sessionCount).isEqualTo(1); } finally { Safely.safelyCall(client::close); } @@ -216,23 +208,23 @@ void connectionLimitIsRespected() throws Exception { BiDi cnn2 = biDiProvider.getImplementation(caps, null).getBiDi(); BiDi cnn3 = biDiProvider.getImplementation(caps, null).getBiDi(); - Assertions.assertThrows( - ConnectionFailedException.class, - () -> biDiProvider.getImplementation(caps, null).getBiDi()); + assertThatThrownBy(() -> biDiProvider.getImplementation(caps, null).getBiDi()) + .isInstanceOf(ConnectionFailedException.class) + .hasMessageStartingWith("JdkWebSocket initial request execution error"); cnn1.close(); BiDi cnn4 = biDiProvider.getImplementation(caps, null).getBiDi(); - Assertions.assertThrows( - ConnectionFailedException.class, - () -> biDiProvider.getImplementation(caps, null).getBiDi()); + assertThatThrownBy(() -> biDiProvider.getImplementation(caps, null).getBiDi()) + .isInstanceOf(ConnectionFailedException.class) + .hasMessageStartingWith("JdkWebSocket initial request execution error"); cnn2.close(); cnn3.close(); BiDi cnn5 = biDiProvider.getImplementation(caps, null).getBiDi(); BiDi cnn6 = biDiProvider.getImplementation(caps, null).getBiDi(); - Assertions.assertThrows( - ConnectionFailedException.class, - () -> biDiProvider.getImplementation(caps, null).getBiDi()); + assertThatThrownBy(() -> biDiProvider.getImplementation(caps, null).getBiDi()) + .isInstanceOf(ConnectionFailedException.class) + .hasMessageStartingWith("JdkWebSocket initial request execution error"); cnn4.close(); cnn5.close(); diff --git a/java/test/org/openqa/selenium/grid/router/EndToEndTest.java b/java/test/org/openqa/selenium/grid/router/EndToEndTest.java index 05daa0c19ad03..1efa077023eea 100644 --- a/java/test/org/openqa/selenium/grid/router/EndToEndTest.java +++ b/java/test/org/openqa/selenium/grid/router/EndToEndTest.java @@ -19,8 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.openqa.selenium.json.Json.MAP_TYPE; import static org.openqa.selenium.remote.http.Contents.asJson; import static org.openqa.selenium.remote.http.Contents.string; @@ -60,11 +58,7 @@ import org.openqa.selenium.json.JsonOutput; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.SessionId; -import org.openqa.selenium.remote.http.Contents; -import org.openqa.selenium.remote.http.HttpClient; -import org.openqa.selenium.remote.http.HttpHandler; -import org.openqa.selenium.remote.http.HttpRequest; -import org.openqa.selenium.remote.http.HttpResponse; +import org.openqa.selenium.remote.http.*; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.testing.Safely; import org.openqa.selenium.testing.TearDownFixture; @@ -237,19 +231,20 @@ void shouldAllowPassthroughForW3CMode(Supplier values) { HttpResponse response = client.execute(request); - assertEquals(200, response.getStatus()); + assertThat(response.getStatus()).isEqualTo(200); Map topLevel = json.toType(string(response), MAP_TYPE); - // There should not be a numeric status field - assertFalse(topLevel.containsKey("status"), string(request)); + assertThat(topLevel) + .as("There should not be a numeric status field") + .doesNotContainKey("status"); // And the value should have all the good stuff in it: the session id and the capabilities Map value = (Map) topLevel.get("value"); assertThat(value.get("sessionId")).isInstanceOf(String.class); Map caps = (Map) value.get("capabilities"); - assertEquals("cheese", caps.get("browserName")); + assertThat(caps.get("browserName")).isEqualTo("cheese"); } @ParameterizedTest diff --git a/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java b/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java index df5aa945908a8..de96b45c7f538 100644 --- a/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java +++ b/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java @@ -17,7 +17,9 @@ package org.openqa.selenium.grid.router; +import static java.time.Duration.ofSeconds; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.HasDownloads.DownloadedFile; import static org.openqa.selenium.remote.CapabilityType.ENABLE_DOWNLOADS; import static org.openqa.selenium.testing.drivers.Browser.IE; @@ -26,19 +28,14 @@ import java.io.File; import java.io.IOException; import java.io.StringReader; -import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.time.Duration; -import java.util.LinkedList; +import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.stream.Collectors; 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.*; @@ -62,9 +59,8 @@ class RemoteWebDriverDownloadTest { private Server server; private NettyAppServer appServer; private Capabilities capabilities; - private final List tearDowns = new LinkedList<>(); - private final ExecutorService executor = - Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); + private WebDriver driver; + private final List tearDowns = new ArrayList<>(2); @BeforeEach public void setupServers() { @@ -96,61 +92,41 @@ public void setupServers() { @AfterEach public void tearDown() { + if (driver != null) { + driver.quit(); + } tearDowns.parallelStream().forEach(Safely::safelyCall); - executor.shutdownNow(); } @Test @Ignore(IE) @Ignore(SAFARI) void canListDownloadedFiles() { - URL gridUrl = server.getUrl(); - WebDriver driver = new RemoteWebDriver(gridUrl, capabilities); - driver = new Augmenter().augment(driver); + driver = createWebdriver(capabilities); driver.get(appServer.whereIs("downloads/download.html")); driver.findElement(By.id("file-1")).click(); driver.findElement(By.id("file-2")).click(); + waitForDownloadedFiles(driver, 2); - HasDownloads hasDownloads = (HasDownloads) driver; - new WebDriverWait(driver, Duration.ofSeconds(5)) - .until( - d -> - hasDownloads.getDownloadableFiles().stream() - // ensure we hit no temporary file created by the browser while - // downloading - .filter((f) -> FILE_EXTENSIONS.stream().anyMatch(f::endsWith)) - .count() - == 2); - - List downloadableFiles = hasDownloads.getDownloadableFiles(); + @SuppressWarnings("deprecation") + List downloadableFiles = ((HasDownloads) driver).getDownloadableFiles(); assertThat(downloadableFiles).contains("file_1.txt", "file_2.jpg"); - List downloadedFiles = hasDownloads.getDownloadedFiles(); + List downloadedFiles = ((HasDownloads) driver).getDownloadedFiles(); assertThat(downloadedFiles.stream().map(f -> f.getName()).collect(Collectors.toList())) .contains("file_1.txt", "file_2.jpg"); - - driver.quit(); } @Test @Ignore(IE) @Ignore(SAFARI) void canDownloadFiles() throws IOException { - URL gridUrl = server.getUrl(); - WebDriver driver = new RemoteWebDriver(gridUrl, capabilities); - driver = new Augmenter().augment(driver); + driver = createWebdriver(capabilities); driver.get(appServer.whereIs("downloads/download.html")); driver.findElement(By.id("file-1")).click(); - - new WebDriverWait(driver, Duration.ofSeconds(5)) - .until( - d -> - ((HasDownloads) d) - .getDownloadableFiles().stream() - // ensure we hit no temporary file created by the browser while downloading - .anyMatch((f) -> FILE_EXTENSIONS.stream().anyMatch(f::endsWith))); + waitForDownloadedFiles(driver, 1); DownloadedFile file = ((HasDownloads) driver).getDownloadedFiles().get(0); @@ -161,49 +137,60 @@ void canDownloadFiles() throws IOException { assertThat(localFile).hasName(file.getName()); assertThat(localFile).hasSize(file.getSize()); assertThat(localFile).content().isEqualToIgnoringNewLines("Hello, World!"); - - driver.quit(); } @Test @Ignore(IE) @Ignore(SAFARI) void testCanDeleteFiles() { - URL gridUrl = server.getUrl(); - WebDriver driver = new RemoteWebDriver(gridUrl, capabilities); + driver = createWebdriver(capabilities); driver.get(appServer.whereIs("downloads/download.html")); driver.findElement(By.id("file-1")).click(); + waitForDownloadedFiles(driver, 1); - new WebDriverWait(driver, Duration.ofSeconds(5)) - .until( - d -> - ((HasDownloads) d) - .getDownloadableFiles().stream() - // ensure we hit no temporary file created by the browser while downloading - .anyMatch((f) -> FILE_EXTENSIONS.stream().anyMatch(f::endsWith))); - - driver = new Augmenter().augment(driver); ((HasDownloads) driver).deleteDownloadableFiles(); - List afterDeleteNames = ((HasDownloads) driver).getDownloadableFiles(); - assertThat(afterDeleteNames.isEmpty()).isTrue(); - - driver.quit(); + var afterDeleteNames = ((HasDownloads) driver).getDownloadedFiles(); + assertThat(afterDeleteNames).isEmpty(); } @Test void errorsWhenCapabilityMissing() { - URL gridUrl = server.getUrl(); Browser browser = Browser.detect(); Capabilities caps = new PersistentCapabilities(Objects.requireNonNull(browser).getCapabilities()) .setCapability(ENABLE_DOWNLOADS, false); - WebDriver driver = new RemoteWebDriver(gridUrl, caps); - Assertions.assertThrows( - WebDriverException.class, - () -> ((HasDownloads) driver).getDownloadableFiles(), - "You must enable downloads in order to work with downloadable files"); + driver = createWebdriver(caps); + assertThatThrownBy(() -> ((HasDownloads) driver).getDownloadedFiles()) + .isInstanceOf(WebDriverException.class) + .hasMessageStartingWith( + "You must enable downloads in order to work with downloadable files"); + + //noinspection deprecation + assertThatThrownBy(() -> ((HasDownloads) driver).getDownloadableFiles()) + .isInstanceOf(WebDriverException.class) + .hasMessageStartingWith( + "You must enable downloads in order to work with downloadable files"); + } + + private WebDriver createWebdriver(Capabilities capabilities) { + return new Augmenter().augment(new RemoteWebDriver(server.getUrl(), capabilities)); + } + + /** ensure we hit no temporary file created by the browser while downloading */ + private void waitForDownloadedFiles(WebDriver driver, int expectedFilesCount) { + HasDownloads hasDownloads = (HasDownloads) driver; + + new WebDriverWait(driver, ofSeconds(5)) + .until( + __ -> { + long actualFilesCount = + hasDownloads.getDownloadedFiles().stream() + .filter((f) -> FILE_EXTENSIONS.stream().anyMatch(f::hasExtension)) + .count(); + return actualFilesCount == expectedFilesCount; + }); } } diff --git a/java/test/org/openqa/selenium/grid/router/RouterTest.java b/java/test/org/openqa/selenium/grid/router/RouterTest.java index 63505088a4359..219b2788a07b5 100644 --- a/java/test/org/openqa/selenium/grid/router/RouterTest.java +++ b/java/test/org/openqa/selenium/grid/router/RouterTest.java @@ -18,11 +18,6 @@ package org.openqa.selenium.grid.router; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.openqa.selenium.grid.data.Availability.DOWN; import static org.openqa.selenium.grid.data.Availability.UP; import static org.openqa.selenium.json.Json.MAP_TYPE; @@ -46,12 +41,7 @@ import org.openqa.selenium.SessionNotCreatedException; import org.openqa.selenium.events.EventBus; import org.openqa.selenium.events.local.GuavaEventBus; -import org.openqa.selenium.grid.data.Availability; -import org.openqa.selenium.grid.data.CreateSessionResponse; -import org.openqa.selenium.grid.data.DefaultSlotMatcher; -import org.openqa.selenium.grid.data.RequestId; -import org.openqa.selenium.grid.data.Session; -import org.openqa.selenium.grid.data.SessionRequest; +import org.openqa.selenium.grid.data.*; import org.openqa.selenium.grid.distributor.Distributor; import org.openqa.selenium.grid.distributor.local.LocalDistributor; import org.openqa.selenium.grid.distributor.selector.DefaultSlotSelector; @@ -86,7 +76,7 @@ class RouterTest { private static Map getStatus(Router router) { HttpResponse response = router.execute(new HttpRequest(GET, "/status")); Map status = Values.get(response, MAP_TYPE); - assertNotNull(status); + assertThat(status).isNotNull(); return status; } @@ -156,7 +146,7 @@ public void setUp() { @Test void shouldListAnEmptyDistributorAsMeaningTheGridIsNotReady() { Map status = getStatus(router); - assertFalse((Boolean) status.get("ready")); + assertThat((Boolean) status.get("ready")).isFalse(); } @Test @@ -173,7 +163,7 @@ void addingANodeThatIsDownMeansTheGridIsNotReady() throws URISyntaxException { waitUntilNotReady(router, Duration.ofSeconds(5)); Map status = getStatus(router); - assertFalse((Boolean) status.get("ready"), status.toString()); + assertThat(status.get("ready")).as(() -> status.toString()).isEqualTo(false); } @Test @@ -229,12 +219,12 @@ id, secondNodeUri, new ImmutableCapabilities(), caps, Instant.now()))) @SuppressWarnings("unchecked") List> nodes = (List>) status.get("nodes"); - assertEquals(2, nodes.size()); + assertThat(nodes).hasSize(2); String firstNodeId = (String) nodes.get(0).get("id"); String secondNodeId = (String) nodes.get(1).get("id"); - assertNotEquals(firstNodeId, secondNodeId); + assertThat(secondNodeId).isNotEqualTo(firstNodeId); } @Test @@ -266,7 +256,7 @@ void ifNodesHaveSpareSlotsButAlreadyHaveMaxSessionsGridIsNotReady() throws URISy waitUntilReady(router, Duration.ofSeconds(5)); Map status = getStatus(router); - assertTrue((Boolean) status.get("ready"), status.toString()); + assertThat((Boolean) status.get("ready")).as(() -> status.toString()).isEqualTo(true); SessionRequest sessionRequest = new SessionRequest( @@ -280,7 +270,7 @@ void ifNodesHaveSpareSlotsButAlreadyHaveMaxSessionsGridIsNotReady() throws URISy Either response = distributor.newSession(sessionRequest); - assertTrue(response.isRight()); + assertThat(response.isRight()).isTrue(); Session session = response.right().getSession(); assertThat(session).isNotNull(); diff --git a/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java b/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java index 03f249dba1758..6a96ee6070ab8 100644 --- a/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java +++ b/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java @@ -328,7 +328,7 @@ void shouldRemoveSessionAfterNodeIsDown() throws URISyntaxException { ImmutableMap.of(), ImmutableMap.of())); assertThat(sessionResponse.isLeft()).isTrue(); - assertThat(distributor.getStatus().getNodes().isEmpty()).isTrue(); + assertThat(distributor.getStatus().getNodes()).isEmpty(); } } diff --git a/java/test/org/openqa/selenium/grid/router/StressTest.java b/java/test/org/openqa/selenium/grid/router/StressTest.java index 2631e35b6f206..499caf4bad372 100644 --- a/java/test/org/openqa/selenium/grid/router/StressTest.java +++ b/java/test/org/openqa/selenium/grid/router/StressTest.java @@ -20,7 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.concurrent.TimeUnit.MINUTES; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.remote.CapabilityType.ENABLE_DOWNLOADS; import java.io.StringReader; @@ -164,28 +164,23 @@ void multipleSimultaneousSessionsTimedOut() throws Exception { // note: As soon as the session cleanup of the node is performed, the grid is unable // to route the request. All commands to a session in this state will fail with: // "Unable to find session with ID:" - NoSuchSessionException exception = - assertThrows(NoSuchSessionException.class, driver::getTitle); - assertThat(exception.getMessage()) + + assertThatThrownBy(driver::getTitle) + .isInstanceOf(NoSuchSessionException.class) + .as("the session timed out. Either cleanup is pending, or cleanup is done.") .matches( - (msg) -> - // the session timed out, the cleanup is pending - msg.startsWith("Cannot find session with id:") - // the session timed out, the cleanup is done - || msg.startsWith("Unable to find session with ID:"), - "Cannot find session … / Unable to find session …"); - WebDriverException webDriverException = - assertThrows( - WebDriverException.class, - () -> ((RemoteWebDriver) driver).getDownloadableFiles()); - assertThat(webDriverException.getMessage()) + e -> + e.getMessage().startsWith("Cannot find session with id:") + || e.getMessage().startsWith("Unable to find session with ID:")); + + assertThatThrownBy(() -> ((RemoteWebDriver) driver).getDownloadedFiles()) + .isInstanceOf(WebDriverException.class) + .as("The session timed out. Either the cleanup is pending or cleanup is done.") .matches( - (msg) -> - // the session timed out, the cleanup is pending - msg.startsWith("Cannot find downloads file system for session id:") - // the session timed out, the cleanup is done - || msg.startsWith("Unable to find session with ID:"), - "Cannot find downloads … / Unable to find session …"); + e -> + e.getMessage() + .startsWith("Cannot find downloads file system for session id:") + || e.getMessage().startsWith("Unable to find session with ID:")); }, executor); } diff --git a/java/test/org/openqa/selenium/grid/server/BaseServerOptionsTest.java b/java/test/org/openqa/selenium/grid/server/BaseServerOptionsTest.java index c92225edfe7a1..2beb9b99720c1 100644 --- a/java/test/org/openqa/selenium/grid/server/BaseServerOptionsTest.java +++ b/java/test/org/openqa/selenium/grid/server/BaseServerOptionsTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium.grid.server; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.net.URISyntaxException; @@ -52,11 +52,10 @@ void externalUriFailsForNonUriStrings() { BaseServerOptions options = new BaseServerOptions(new MapConfig(Map.of("server", Map.of("external-url", "not a URL")))); - Exception exception = assertThrows(RuntimeException.class, options::getExternalUri); - - assertThat(exception.getMessage()) + assertThatThrownBy(options::getExternalUri) .as("External URI must be parseable as URI.") - .isEqualTo( + .isInstanceOf(RuntimeException.class) + .hasMessage( "Supplied external URI is invalid: Illegal character in path at index 3: not a URL"); } diff --git a/java/test/org/openqa/selenium/grid/sessionmap/SessionMapTest.java b/java/test/org/openqa/selenium/grid/sessionmap/SessionMapTest.java index 18aee992c4077..d74036074bb71 100644 --- a/java/test/org/openqa/selenium/grid/sessionmap/SessionMapTest.java +++ b/java/test/org/openqa/selenium/grid/sessionmap/SessionMapTest.java @@ -21,7 +21,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.URI; import java.net.URISyntaxException; @@ -79,7 +78,7 @@ public void setUp() throws URISyntaxException { @Test void shouldBeAbleToAddASession() { - assertTrue(remote.add(expected)); + assertThat(remote.add(expected)).isTrue(); assertThat(local.get(id)).isEqualTo(expected); } diff --git a/java/test/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMapTest.java b/java/test/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMapTest.java index 9294861f44c8c..7fa66d0afc987 100644 --- a/java/test/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMapTest.java +++ b/java/test/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMapTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium.grid.sessionmap.jdbc; +import static java.util.UUID.randomUUID; import static org.assertj.core.api.Assertions.*; -import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; import java.net.URISyntaxException; @@ -71,35 +71,29 @@ public static void killDBConnection() throws SQLException { @Test void shouldThrowNoSuchSessionExceptionIfSessionDoesNotExists() { - assertThrows( - NoSuchSessionException.class, - () -> { - SessionMap sessions = getSessionMap(); - - sessions.get(new SessionId(UUID.randomUUID())); - }); + SessionMap sessions = getSessionMap(); + UUID sessionId = randomUUID(); + assertThatThrownBy(() -> sessions.get(new SessionId(sessionId))) + .isInstanceOf(NoSuchSessionException.class) + .hasMessageStartingWith("Unable to find session with id: " + sessionId); } @Test void shouldThrowIllegalArgumentExceptionIfConnectionObjectIsNull() { - assertThrows( - IllegalArgumentException.class, - () -> { - SessionMap sessions = new JdbcBackedSessionMap(tracer, null, bus); - }); + assertThatThrownBy(() -> new JdbcBackedSessionMap(tracer, null, bus)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("JDBC Connection Object must be set"); } @Test void shouldThrowNoSuchSessionExceptionIfTableDoesNotExist() throws SQLException { - assertThrows( - JdbcException.class, - () -> { - Connection connection2 = DriverManager.getConnection("jdbc:hsqldb:mem:testdb2", "SA", ""); - - SessionMap sessions = new JdbcBackedSessionMap(tracer, connection2, bus); + Connection connection2 = DriverManager.getConnection("jdbc:hsqldb:mem:testdb2", "SA", ""); + SessionMap sessions = new JdbcBackedSessionMap(tracer, connection2, bus); + UUID sessionId = randomUUID(); - sessions.get(new SessionId(UUID.randomUUID())); - }); + assertThatThrownBy(() -> sessions.get(new SessionId(sessionId))) + .isInstanceOf(JdbcException.class) + .hasMessageContaining("object not found: SESSIONS_MAP"); } @Test @@ -108,7 +102,7 @@ void canCreateAJdbcBackedSessionMap() throws URISyntaxException { Session expected = new Session( - new SessionId(UUID.randomUUID()), + new SessionId(randomUUID()), new URI("http://example.com/foo"), new ImmutableCapabilities("foo", "bar"), new ImmutableCapabilities("key", "value"), @@ -128,7 +122,7 @@ void shouldBeAbleToRemoveSessions() throws URISyntaxException { Session expected = new Session( - new SessionId(UUID.randomUUID()), + new SessionId(randomUUID()), new URI("http://example.com/foo"), new ImmutableCapabilities("foo", "bar"), new ImmutableCapabilities("key", "value"), diff --git a/java/test/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMapTest.java b/java/test/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMapTest.java index c1f283108769c..a6bb04b161667 100644 --- a/java/test/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMapTest.java +++ b/java/test/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMapTest.java @@ -17,14 +17,13 @@ package org.openqa.selenium.grid.sessionmap.redis; +import static java.util.UUID.randomUUID; import static org.assertj.core.api.Assertions.*; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.openqa.selenium.testing.Safely.safelyCall; import java.net.URI; import java.net.URISyntaxException; import java.time.Instant; -import java.util.UUID; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -43,17 +42,15 @@ class RedisBackedSessionMapTest { private RedisServer server; private EventBus bus; - private Tracer tracer = DefaultTestTracer.createTracer(); - private URI uri; private RedisBackedSessionMap sessions; @BeforeEach public void setUp() throws URISyntaxException { - uri = new URI("redis://localhost:" + PortProber.findFreePort()); + URI uri = new URI("redis://localhost:" + PortProber.findFreePort()); server = RedisServer.builder().port(uri.getPort()).build(); server.start(); - tracer = DefaultTestTracer.createTracer(); + Tracer tracer = DefaultTestTracer.createTracer(); bus = new GuavaEventBus(); sessions = new RedisBackedSessionMap(tracer, uri, bus); } @@ -67,18 +64,17 @@ public void tearDownRedisServer() { @Test void shouldThrowANoSuchSessionExceptionIfTheSessionDoesNotExist() { - assertThrows( - NoSuchSessionException.class, - () -> { - sessions.get(new SessionId(UUID.randomUUID())); - }); + String sessionId = randomUUID().toString(); + assertThatThrownBy(() -> sessions.get(new SessionId(sessionId))) + .isInstanceOf(NoSuchSessionException.class) + .hasMessageContaining(sessionId); } @Test void canGetTheUriOfASessionWithoutNeedingUrl() throws URISyntaxException { Session expected = new Session( - new SessionId(UUID.randomUUID()), + new SessionId(randomUUID()), new URI("http://example.com/foo"), new ImmutableCapabilities(), new ImmutableCapabilities(), @@ -94,7 +90,7 @@ void canGetTheUriOfASessionWithoutNeedingUrl() throws URISyntaxException { void canCreateARedisBackedSessionMap() throws URISyntaxException { Session expected = new Session( - new SessionId(UUID.randomUUID()), + new SessionId(randomUUID()), new URI("http://example.com/foo"), new ImmutableCapabilities(), new ImmutableCapabilities("cheese", "beyaz peynir"), @@ -110,7 +106,7 @@ void canCreateARedisBackedSessionMap() throws URISyntaxException { void shouldBeAbleToRemoveSessions() throws URISyntaxException { Session expected = new Session( - new SessionId(UUID.randomUUID()), + new SessionId(randomUUID()), new URI("http://example.com/foo"), new ImmutableCapabilities(), new ImmutableCapabilities("cheese", "beyaz peynir"), diff --git a/java/test/org/openqa/selenium/grid/web/ReverseProxyHandlerTest.java b/java/test/org/openqa/selenium/grid/web/ReverseProxyHandlerTest.java index f44775e2b7b41..fe367093bf815 100644 --- a/java/test/org/openqa/selenium/grid/web/ReverseProxyHandlerTest.java +++ b/java/test/org/openqa/selenium/grid/web/ReverseProxyHandlerTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.grid.web; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.net.MalformedURLException; import java.net.URISyntaxException; @@ -48,7 +48,7 @@ void shouldForwardRequestsToEndPoint() HttpResponse response = handler.execute(req); // HTTP headers are case insensitive. - assertEquals("Cake", response.getHeader("x-cheese")); + assertThat(response.getHeader("x-cheese")).isEqualTo("Cake"); } } } diff --git a/java/test/org/openqa/selenium/grid/web/TeeReaderTest.java b/java/test/org/openqa/selenium/grid/web/TeeReaderTest.java index 23b37ffd0d99d..713c9ab8421c5 100644 --- a/java/test/org/openqa/selenium/grid/web/TeeReaderTest.java +++ b/java/test/org/openqa/selenium/grid/web/TeeReaderTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.grid.web; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.Reader; import java.io.StringReader; @@ -40,11 +40,11 @@ void shouldDuplicateStreams() { try (JsonInput reader = new Json().newInput(tee)) { reader.beginObject(); - assertEquals("key", reader.nextName()); + assertThat(reader.nextName()).isEqualTo("key"); reader.skipValue(); reader.endObject(); - assertEquals(expected, writer.toString()); + assertThat(writer.toString()).isEqualTo(expected); } } } diff --git a/java/test/org/openqa/selenium/interactions/ActionDurationTest.java b/java/test/org/openqa/selenium/interactions/ActionDurationTest.java index f9d603390eedf..f3ead869c7e2b 100644 --- a/java/test/org/openqa/selenium/interactions/ActionDurationTest.java +++ b/java/test/org/openqa/selenium/interactions/ActionDurationTest.java @@ -17,9 +17,8 @@ package org.openqa.selenium.interactions; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static java.time.Duration.ofMillis; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import org.junit.jupiter.api.Tag; @@ -37,11 +36,11 @@ void shouldScrollToElementWithCustomDuration() { appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); WebElement iframe = driver.findElement(By.tagName("iframe")); - assertFalse(inViewport(iframe)); + assertThat(inViewport(iframe)).isFalse(); new Actions(driver, Duration.ofMillis(111)).scrollToElement(iframe).perform(); - assertTrue(inViewport(iframe)); + assertThat(inViewport(iframe)).isTrue(); } @Test @@ -53,19 +52,19 @@ void shouldScrollFromViewportByGivenAmountWithCustomDuration() { new Actions(driver, Duration.ofMillis(111)).scrollByAmount(0, deltaY).perform(); - assertTrue(inViewport(footer)); + assertThat(inViewport(footer)).isTrue(); } @Test void shouldBeDefaultActionDuration250ms() { Actions actions = new Actions(driver); - assertEquals(Duration.ofMillis(250), actions.getActionDuration()); + assertThat(actions.getActionDuration()).isEqualTo(ofMillis(250)); } @Test void shouldBeCustomDuration110ms() { Actions actions = new Actions(driver, Duration.ofMillis(110)); - assertEquals(Duration.ofMillis(110), actions.getActionDuration()); + assertThat(actions.getActionDuration()).isEqualTo(ofMillis(110)); } private boolean inViewport(WebElement element) { diff --git a/java/test/org/openqa/selenium/interactions/DefaultWheelTest.java b/java/test/org/openqa/selenium/interactions/DefaultWheelTest.java index 62d90f4af0e70..51f8507dd1c39 100644 --- a/java/test/org/openqa/selenium/interactions/DefaultWheelTest.java +++ b/java/test/org/openqa/selenium/interactions/DefaultWheelTest.java @@ -17,9 +17,8 @@ package org.openqa.selenium.interactions; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; @@ -41,11 +40,11 @@ void shouldScrollToElement() { appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); WebElement iframe = driver.findElement(By.tagName("iframe")); - assertFalse(inViewport(iframe)); + assertThat(inViewport(iframe)).isFalse(); getBuilder(driver).scrollToElement(iframe).perform(); - assertTrue(inViewport(iframe)); + assertThat(inViewport(iframe)).isTrue(); } @Test @@ -59,7 +58,7 @@ void shouldScrollFromElementByGivenAmount() { driver.switchTo().frame(iframe); WebElement checkbox = driver.findElement(By.name("scroll_checkbox")); - assertTrue(inViewport(checkbox)); + assertThat(inViewport(checkbox)).isTrue(); } @Test @@ -74,22 +73,24 @@ void shouldScrollFromElementByGivenAmountWithOffset() { WebElement iframe = driver.findElement(By.tagName("iframe")); driver.switchTo().frame(iframe); WebElement checkbox = driver.findElement(By.name("scroll_checkbox")); - assertTrue(inViewport(checkbox)); + assertThat(inViewport(checkbox)).isTrue(); } @Test void throwErrorWhenElementOriginIsOutOfViewport() { - assertThrows( - MoveTargetOutOfBoundsException.class, - () -> { - driver.get( - appServer.whereIs( - "scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); - WebElement footer = driver.findElement(By.tagName("footer")); - WheelInput.ScrollOrigin scrollOrigin = WheelInput.ScrollOrigin.fromElement(footer, 0, 50); - - getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).perform(); - }); + assertThatThrownBy( + () -> { + driver.get( + appServer.whereIs( + "scrolling_tests/frame_with_nested_scrolling_frame_out_of_view.html")); + WebElement footer = driver.findElement(By.tagName("footer")); + WheelInput.ScrollOrigin scrollOrigin = + WheelInput.ScrollOrigin.fromElement(footer, 0, 50); + + getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).perform(); + }) + .isInstanceOf(MoveTargetOutOfBoundsException.class) + .hasMessageContaining("move target out of bounds"); } @Test @@ -101,7 +102,7 @@ void shouldScrollFromViewportByGivenAmount() { getBuilder(driver).scrollByAmount(0, deltaY).perform(); - assertTrue(inViewport(footer)); + assertThat(inViewport(footer)).isTrue(); } @Test @@ -114,19 +115,21 @@ void shouldScrollFromViewportByGivenAmountFromOrigin() { WebElement iframe = driver.findElement(By.tagName("iframe")); driver.switchTo().frame(iframe); WebElement checkbox = driver.findElement(By.name("scroll_checkbox")); - assertTrue(inViewport(checkbox)); + assertThat(inViewport(checkbox)).isTrue(); } @Test void throwErrorWhenOriginOffsetIsOutOfViewport() { - assertThrows( - MoveTargetOutOfBoundsException.class, - () -> { - driver.get(appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame.html")); - WheelInput.ScrollOrigin scrollOrigin = WheelInput.ScrollOrigin.fromViewport(-10, -10); - - getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).perform(); - }); + assertThatThrownBy( + () -> { + driver.get( + appServer.whereIs("scrolling_tests/frame_with_nested_scrolling_frame.html")); + WheelInput.ScrollOrigin scrollOrigin = WheelInput.ScrollOrigin.fromViewport(-10, -10); + + getBuilder(driver).scrollFromOrigin(scrollOrigin, 0, 200).perform(); + }) + .isInstanceOf(MoveTargetOutOfBoundsException.class) + .hasMessageContaining("move target out of bounds"); } private boolean inViewport(WebElement element) { diff --git a/java/test/org/openqa/selenium/io/TemporaryFilesystemTest.java b/java/test/org/openqa/selenium/io/TemporaryFilesystemTest.java index 8b0cca288d3b6..0f6c7f3f24b6a 100644 --- a/java/test/org/openqa/selenium/io/TemporaryFilesystemTest.java +++ b/java/test/org/openqa/selenium/io/TemporaryFilesystemTest.java @@ -18,7 +18,6 @@ package org.openqa.selenium.io; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; @@ -45,7 +44,7 @@ public void setUp() { public void tearDown() throws IOException { if (baseForTest.exists()) { tmpFs.deleteTemporaryFiles(); - assertTrue(baseForTest.delete()); + assertThat(baseForTest.delete()).isTrue(); } } diff --git a/java/test/org/openqa/selenium/netty/server/NettyServerTest.java b/java/test/org/openqa/selenium/netty/server/NettyServerTest.java index d911e7cc8f875..b1a832ac2a426 100644 --- a/java/test/org/openqa/selenium/netty/server/NettyServerTest.java +++ b/java/test/org/openqa/selenium/netty/server/NettyServerTest.java @@ -18,10 +18,7 @@ package org.openqa.selenium.netty.server; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.remote.http.Contents.utf8String; import static org.openqa.selenium.remote.http.HttpMethod.DELETE; import static org.openqa.selenium.remote.http.HttpMethod.GET; @@ -32,7 +29,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.grid.config.CompoundConfig; @@ -104,9 +100,9 @@ void shouldDisableAllowOrigin() { request.setHeader("Accept", "*/*"); HttpResponse response = client.execute(request); - assertNull( - response.getHeader("Access-Control-Allow-Origin"), - "Access-Control-Allow-Origin should be null"); + assertThat(response.getHeader("Access-Control-Allow-Origin")) + .as("Access-Control-Allow-Origin should be null") + .isNull(); } @Test @@ -115,7 +111,7 @@ void shouldAllowCORS() { new CompoundConfig( new MapConfig(ImmutableMap.of("server", ImmutableMap.of("allow-cors", "true")))); BaseServerOptions options = new BaseServerOptions(cfg); - assertTrue(options.getAllowCORS(), "Allow CORS should be enabled"); + assertThat(options.getAllowCORS()).as("Allow CORS should be enabled").isTrue(); Server server = new NettyServer(options, req -> new HttpResponse()).start(); @@ -126,10 +122,9 @@ void shouldAllowCORS() { request.setHeader("Accept", "*/*"); HttpResponse response = client.execute(request); - assertEquals( - "*", - response.getHeader("Access-Control-Allow-Origin"), - "Access-Control-Allow-Origin should be equal to origin in request header"); + assertThat(response.getHeader("Access-Control-Allow-Origin")) + .as("Access-Control-Allow-Origin should be equal to origin in request header") + .isEqualTo("*"); } @Test @@ -140,11 +135,11 @@ void shouldNotBindToHost() { ImmutableMap.of( "server", ImmutableMap.of("bind-host", "false", "host", "anyRandomHost")))); BaseServerOptions options = new BaseServerOptions(cfg); - assertFalse(options.getBindHost(), "Bind to host should be disabled"); + assertThat(options.getBindHost()).as("Bind to host should be disabled").isFalse(); Server server = new NettyServer(options, req -> new HttpResponse()).start(); - assertEquals("anyRandomHost", server.getUrl().getHost()); + assertThat(server.getUrl().getHost()).isEqualTo("anyRandomHost"); } @Test @@ -171,17 +166,19 @@ void doesInterruptPending() throws Exception { .baseUri(server.getUrl().toURI()); // provoke a client timeout - Assertions.assertThrows( - TimeoutException.class, - () -> { - try (HttpClient client = HttpClient.Factory.createDefault().createClient(config)) { - HttpRequest request = new HttpRequest(DELETE, "/session"); - request.setHeader("Accept", "*/*"); - client.execute(request); - } - }); - - assertTrue(interrupted.await(1000, TimeUnit.MILLISECONDS), "The handling was interrupted"); + assertThatThrownBy( + () -> { + try (HttpClient client = HttpClient.Factory.createDefault().createClient(config)) { + HttpRequest request = new HttpRequest(DELETE, "/session"); + request.setHeader("Accept", "*/*"); + client.execute(request); + } + }) + .isInstanceOf(TimeoutException.class); + + assertThat(interrupted.await(1000, TimeUnit.MILLISECONDS)) + .as("The handling was interrupted") + .isTrue(); } private void outputHeaders(HttpResponse res) { diff --git a/java/test/org/openqa/selenium/netty/server/WebSocketServingTest.java b/java/test/org/openqa/selenium/netty/server/WebSocketServingTest.java index c190e7e2b3b42..f92a4c6db3242 100644 --- a/java/test/org/openqa/selenium/netty/server/WebSocketServingTest.java +++ b/java/test/org/openqa/selenium/netty/server/WebSocketServingTest.java @@ -20,7 +20,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.remote.http.Contents.utf8String; import static org.openqa.selenium.remote.http.HttpMethod.GET; @@ -62,15 +62,17 @@ public void shutDown() { @Test void clientShouldThrowAnExceptionIfUnableToConnectToAWebSocketEndPoint() { - assertThrows( - ConnectionFailedException.class, - () -> { - server = new NettyServer(defaultOptions(), req -> new HttpResponse()).start(); + assertThatThrownBy( + () -> { + server = new NettyServer(defaultOptions(), req -> new HttpResponse()).start(); - HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl()); + HttpClient client = HttpClient.Factory.createDefault().createClient(server.getUrl()); - client.openSocket(new HttpRequest(GET, "/does-not-exist"), new WebSocket.Listener() {}); - }); + client.openSocket( + new HttpRequest(GET, "/does-not-exist"), new WebSocket.Listener() {}); + }) + .isInstanceOf(ConnectionFailedException.class) + .hasMessageStartingWith("JdkWebSocket initial request execution error"); } @Test diff --git a/java/test/org/openqa/selenium/remote/NewSessionPayloadTest.java b/java/test/org/openqa/selenium/remote/NewSessionPayloadTest.java index 866dda8916f11..c0f12c97948da 100644 --- a/java/test/org/openqa/selenium/remote/NewSessionPayloadTest.java +++ b/java/test/org/openqa/selenium/remote/NewSessionPayloadTest.java @@ -26,8 +26,9 @@ import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.openqa.selenium.Platform.LINUX; import static org.openqa.selenium.json.Json.MAP_TYPE; +import static org.openqa.selenium.remote.Dialect.W3C; import com.google.common.collect.ImmutableMap; import java.io.IOException; @@ -39,7 +40,6 @@ import org.junit.jupiter.api.Test; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; -import org.openqa.selenium.Platform; import org.openqa.selenium.json.Json; import org.openqa.selenium.remote.http.Contents; @@ -53,13 +53,13 @@ void shouldIndicateDownstreamW3cDialect() { "capabilities", singletonMap("alwaysMatch", singletonMap("browserName", "cheese"))); try (NewSessionPayload payload = NewSessionPayload.create(caps)) { - assertEquals(singleton(Dialect.W3C), payload.getDownstreamDialects()); + assertThat(payload.getDownstreamDialects()).isEqualTo(singleton(W3C)); } String json = new Json().toJson(caps); try (NewSessionPayload payload = NewSessionPayload.create(Contents.string(json, StandardCharsets.UTF_8))) { - assertEquals(singleton(Dialect.W3C), payload.getDownstreamDialects()); + assertThat(payload.getDownstreamDialects()).isEqualTo(singleton(W3C)); } } @@ -71,8 +71,8 @@ void shouldReturnAlwaysMatchIfNoFirstMatchIsPresent() { "capabilities", singletonMap("alwaysMatch", singletonMap("browserName", "cheese")))); - assertEquals(1, capabilities.size(), capabilities.toString()); - assertEquals("cheese", capabilities.get(0).getBrowserName()); + assertThat(capabilities).as(() -> capabilities.toString()).hasSize(1); + assertThat(capabilities.get(0).getBrowserName()).isEqualTo("cheese"); } @Test @@ -87,9 +87,9 @@ void shouldReturnEachFirstMatchIfNoAlwaysMatchIsPresent() { singletonMap("browserName", "cheese"), singletonMap("browserName", "peas"))))); - assertEquals(2, capabilities.size(), capabilities.toString()); - assertEquals("cheese", capabilities.get(0).getBrowserName()); - assertEquals("peas", capabilities.get(1).getBrowserName()); + assertThat(capabilities).as(() -> capabilities.toString()).hasSize(2); + assertThat(capabilities.get(0).getBrowserName()).isEqualTo("cheese"); + assertThat(capabilities.get(1).getBrowserName()).isEqualTo("peas"); } @Test @@ -100,8 +100,8 @@ void shouldOfferStreamOfW3cCapabilitiesIfPresent() { "capabilities", singletonMap("alwaysMatch", singletonMap("browserName", "peas")))); // We expect a synthetic w3c capability for the mismatching OSS capabilities - assertEquals(1, capabilities.size(), capabilities.toString()); - assertEquals("peas", capabilities.get(0).getBrowserName()); + assertThat(capabilities).as(() -> capabilities.toString()).hasSize(1); + assertThat(capabilities.get(0).getBrowserName()).isEqualTo("peas"); } @Test @@ -117,11 +117,11 @@ void shouldMergeAlwaysAndFirstMatches() { singletonMap("browserName", "cheese"), singletonMap("browserName", "peas"))))); - assertEquals(2, capabilities.size(), capabilities.toString()); - assertEquals("cheese", capabilities.get(0).getBrowserName()); - assertEquals("also cheese", capabilities.get(0).getCapability("se:cake")); - assertEquals("peas", capabilities.get(1).getBrowserName()); - assertEquals("also cheese", capabilities.get(1).getCapability("se:cake")); + assertThat(capabilities).as(() -> capabilities.toString()).hasSize(2); + assertThat(capabilities.get(0).getBrowserName()).isEqualTo("cheese"); + assertThat(capabilities.get(0).getCapability("se:cake")).isEqualTo("also cheese"); + assertThat(capabilities.get(1).getBrowserName()).isEqualTo("peas"); + assertThat(capabilities.get(1).getCapability("se:cake")).isEqualTo("also cheese"); } @Test @@ -132,7 +132,7 @@ void shouldCorrectlyExtractPlatformFromW3cCapabilities() { "capabilities", singletonMap("alwaysMatch", singletonMap("platformName", "linux")))); - assertEquals(Platform.LINUX, capabilities.get(0).getPlatformName()); + assertThat(capabilities.get(0).getPlatformName()).isEqualTo(LINUX); } @Test @@ -172,12 +172,12 @@ void convertEverythingToFirstMatchOnlyIfPayloadContainsAlwaysMatchSectionAndOssC singletonMap("browserName", "foo"), singletonMap("browserName", "firefox"))))); - assertEquals( - asList( - // From the actual W3C capabilities - new ImmutableCapabilities("browserName", "foo", "platformName", "macos"), - new ImmutableCapabilities("browserName", "firefox", "platformName", "macos")), - capabilities); + assertThat(capabilities) + .isEqualTo( + asList( + // From the actual W3C capabilities + new ImmutableCapabilities("browserName", "foo", "platformName", "macos"), + new ImmutableCapabilities("browserName", "firefox", "platformName", "macos"))); } @Test @@ -192,8 +192,8 @@ void forwardsMetaDataAssociatedWithARequest() throws IOException { payload.writeTo(toParse); Map seen = new Json().toType(toParse.toString(), MAP_TYPE); - assertEquals("bob", seen.get("cloud:user")); - assertEquals("there is no cake", seen.get("cloud:key")); + assertThat(seen.get("cloud:user")).isEqualTo("bob"); + assertThat(seen.get("cloud:key")).isEqualTo("there is no cake"); } } @@ -269,7 +269,7 @@ private List create(Map source) { fromDisk = payload.stream().collect(toList()); } - assertEquals(presumablyFromMemory, fromDisk); + assertThat(fromDisk).isEqualTo(presumablyFromMemory); return presumablyFromMemory; } diff --git a/java/test/org/openqa/selenium/remote/http/NativeHttpClientMethodsTest.java b/java/test/org/openqa/selenium/remote/http/NativeHttpClientMethodsTest.java index bce11145c9fb5..9defc7aa51e74 100644 --- a/java/test/org/openqa/selenium/remote/http/NativeHttpClientMethodsTest.java +++ b/java/test/org/openqa/selenium/remote/http/NativeHttpClientMethodsTest.java @@ -18,9 +18,7 @@ package org.openqa.selenium.remote.http; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.net.URI; @@ -67,9 +65,9 @@ void testSendAsyncNative_successful() httpClient.sendAsyncNative(testRequest, HttpResponse.BodyHandlers.ofString()); // Assert - Verify the asynchronous response is correct - assertNotNull(result, "Future should not be null"); + assertThat(result).as("Future should not be null").isNotNull(); HttpResponse response = result.get(5, TimeUnit.SECONDS); - assertNotNull(response, "Response should not be null"); + assertThat(response).as("Response should not be null").isNotNull(); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body()).isEqualTo("Test response body"); } @@ -86,7 +84,7 @@ void testSendNative_successful() throws IOException, InterruptedException { httpClient.sendNative(testRequest, HttpResponse.BodyHandlers.ofString()); // Assert - Verify the synchronous response is correct - assertNotNull(result, "Response should not be null"); + assertThat(result).as("Response should not be null").isNotNull(); assertThat(result.statusCode()).isEqualTo(200); assertThat(result.body()).isEqualTo("Test response body"); } @@ -100,12 +98,14 @@ void testSendNative_successful() throws IOException, InterruptedException { @Test void testSendNative_handlesIOException() { // Arrange - Create a client configured to simulate network failure - TestHttpClient failingClient = new TestHttpClient(true); + try (TestHttpClient failingClient = new TestHttpClient(true)) { - // Act & Assert - Verify that IOException is thrown when network failure occurs - assertThrows( - IOException.class, - () -> failingClient.sendNative(testRequest, HttpResponse.BodyHandlers.ofString())); + // Act & Assert - Verify that IOException is thrown when network failure occurs + assertThatThrownBy( + () -> failingClient.sendNative(testRequest, HttpResponse.BodyHandlers.ofString())) + .isInstanceOf(IOException.class) + .hasMessage("Simulated network error"); + } } /** @@ -121,7 +121,7 @@ void testRequestParameters_validation() { HttpRequest.newBuilder().uri(URI.create("https://httpbin.org/get")).GET().build(); // Assert GET request properties - assertNotNull(getRequest); + assertThat(getRequest).isNotNull(); assertThat(getRequest.method()).isEqualTo("GET"); // Test POST request creation with body and headers @@ -133,9 +133,9 @@ void testRequestParameters_validation() { .build(); // Assert POST request properties including headers - assertNotNull(postRequest); + assertThat(postRequest).isNotNull(); assertThat(postRequest.method()).isEqualTo("POST"); - assertTrue(postRequest.headers().firstValue("Content-Type").isPresent()); + assertThat(postRequest.headers().firstValue("Content-Type").isPresent()).isTrue(); } /** @@ -148,16 +148,16 @@ void testRequestParameters_validation() { void testBodyHandlers_variations() { // Test String handler for regular text responses HttpResponse.BodyHandler stringHandler = HttpResponse.BodyHandlers.ofString(); - assertNotNull(stringHandler); + assertThat(stringHandler).isNotNull(); // Test discarding handler (useful for HEAD requests or when body is not needed) HttpResponse.BodyHandler discardingHandler = HttpResponse.BodyHandlers.discarding(); - assertNotNull(discardingHandler); + assertThat(discardingHandler).isNotNull(); // Test lines handler for streaming large responses line by line HttpResponse.BodyHandler> linesHandler = HttpResponse.BodyHandlers.ofLines(); - assertNotNull(linesHandler); + assertThat(linesHandler).isNotNull(); } /** diff --git a/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java b/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java index 7c0ec902a90db..c6d647f972e90 100644 --- a/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java +++ b/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java @@ -21,6 +21,7 @@ import static java.net.HttpURLConnection.HTTP_OK; import static java.net.HttpURLConnection.HTTP_UNAVAILABLE; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.remote.http.Contents.asJson; import static org.openqa.selenium.remote.http.HttpMethod.GET; @@ -40,7 +41,6 @@ import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.openqa.selenium.TimeoutException; @@ -72,8 +72,9 @@ void canThrowUnexpectedException() { throw new UnsupportedOperationException("Testing"); }); - Assertions.assertThrows( - UnsupportedOperationException.class, () -> handler.execute(new HttpRequest(GET, "/"))); + assertThatThrownBy(() -> handler.execute(new HttpRequest(GET, "/"))) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("Testing"); } @Test @@ -90,13 +91,15 @@ void noUnexpectedRetry() { } }); - Assertions.assertThrows( - StackOverflowError.class, () -> handler.execute(new HttpRequest(GET, "/"))); - Assertions.assertEquals(1, count.get()); + assertThatThrownBy(() -> handler.execute(new HttpRequest(GET, "/"))) + .isInstanceOf(StackOverflowError.class) + .hasMessage("Testing"); + assertThat(count).hasValue(1); - Assertions.assertThrows( - UncheckedIOException.class, () -> handler.execute(new HttpRequest(GET, "/"))); - Assertions.assertEquals(2, count.get()); + assertThatThrownBy(() -> handler.execute(new HttpRequest(GET, "/"))) + .isInstanceOf(UncheckedIOException.class) + .hasMessage("More testing"); + assertThat(count).hasValue(2); } @Test @@ -105,18 +108,18 @@ void canReturnAppropriateFallbackResponse() { new RetryRequest() .andFinally( (HttpRequest request) -> { - throw new TimeoutException(); + throw new TimeoutException("Failed to load in time"); }); - Assertions.assertThrows( - TimeoutException.class, () -> handler1.execute(new HttpRequest(GET, "/"))); + assertThatThrownBy(() -> handler1.execute(new HttpRequest(GET, "/"))) + .isInstanceOf(TimeoutException.class) + .hasMessageStartingWith("Failed to load in time"); HttpHandler handler2 = new RetryRequest() .andFinally((HttpRequest request) -> new HttpResponse().setStatus(HTTP_UNAVAILABLE)); - Assertions.assertEquals( - HTTP_UNAVAILABLE, handler2.execute(new HttpRequest(GET, "/")).getStatus()); + assertThat(handler2.execute(new HttpRequest(GET, "/")).getStatus()).isEqualTo(HTTP_UNAVAILABLE); } @Test @@ -144,8 +147,8 @@ void canReturnAppropriateFallbackResponseWithMultipleThreads() for (int i = 0; i < 1024; i++) { int offset = i * 2; - Assertions.assertThrows(ExecutionException.class, () -> results.get(offset).get()); - Assertions.assertEquals(HTTP_UNAVAILABLE, results.get(offset + 1).get().getStatus()); + assertThatThrownBy(() -> results.get(offset).get()).isInstanceOf(ExecutionException.class); + assertThat(results.get(offset + 1).get().getStatus()).isEqualTo(HTTP_UNAVAILABLE); } executorService.shutdown(); @@ -330,10 +333,9 @@ void shouldRethrowOnConnectFailure() { throw lastThrown.get(); }); - UncheckedIOException thrown = - Assertions.assertThrows( - UncheckedIOException.class, () -> handler.execute(new HttpRequest(GET, "/"))); - assertThat(thrown).isSameAs(lastThrown.get()); + assertThatThrownBy(() -> handler.execute(new HttpRequest(GET, "/"))) + .isInstanceOf(UncheckedIOException.class) + .isSameAs(lastThrown.get()); assertThat(count).hasValue(4); } diff --git a/java/test/org/openqa/selenium/testing/IgnoreComparatorUnitTest.java b/java/test/org/openqa/selenium/testing/IgnoreComparatorUnitTest.java index 65380c5528213..1dcf7a3f5933f 100644 --- a/java/test/org/openqa/selenium/testing/IgnoreComparatorUnitTest.java +++ b/java/test/org/openqa/selenium/testing/IgnoreComparatorUnitTest.java @@ -17,12 +17,11 @@ package org.openqa.selenium.testing; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static java.util.Collections.singleton; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.openqa.selenium.testing.drivers.Browser.IE; -import static org.openqa.selenium.testing.drivers.Browser.SAFARI; +import static org.openqa.selenium.testing.drivers.Browser.*; import java.util.Collections; import java.util.Set; @@ -45,72 +44,70 @@ class IgnoreComparatorUnitTest { @Test void shouldNotIgnoreIfNothingBeingIgnored() { - assertFalse(new IgnoreComparator().shouldIgnore((Ignore) null)); - assertFalse(new IgnoreComparator().shouldIgnore((IgnoreList) null)); + assertThat(new IgnoreComparator().shouldIgnore((Ignore) null)).isFalse(); + assertThat(new IgnoreComparator().shouldIgnore((IgnoreList) null)).isFalse(); } @Test void shouldIgnoreOnlyDriverBeingIgnored() { ignoreComparator.addDriver(SAFARI); - assertTrue( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(SAFARI), CURRENT_PLATFORM_SET))); + assertThat( + ignoreComparator.shouldIgnore(ignoreForDriver(singleton(SAFARI), CURRENT_PLATFORM_SET))) + .isTrue(); } @Test void shouldIgnoreDriverAll() { - assertTrue( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(Browser.ALL), CURRENT_PLATFORM_SET))); + assertThat(ignoreComparator.shouldIgnore(ignoreForDriver(singleton(ALL), CURRENT_PLATFORM_SET))) + .isTrue(); } @Test @Disabled public void shouldNotIgnoreOtherPlatform() { ignoreComparator.addDriver(SAFARI); - assertFalse( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(SAFARI), OTHER_PLATFORM_SET))); + assertThat( + ignoreComparator.shouldIgnore(ignoreForDriver(singleton(SAFARI), OTHER_PLATFORM_SET))) + .isFalse(); } @Test void shouldNotIgnoreOtherBrowser() { ignoreComparator.addDriver(SAFARI); - assertFalse( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(IE), CURRENT_PLATFORM_SET))); + assertThat(ignoreComparator.shouldIgnore(ignoreForDriver(singleton(IE), CURRENT_PLATFORM_SET))) + .isFalse(); } @Test void shouldIgnoreEnabledNativeEventsIfIgnoringEnabled() { ignoreComparator.addDriver(SAFARI); - assertTrue( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(SAFARI), CURRENT_PLATFORM_SET))); + assertThat( + ignoreComparator.shouldIgnore(ignoreForDriver(singleton(SAFARI), CURRENT_PLATFORM_SET))) + .isTrue(); } @Test void shouldIgnoreDisabledNativeEventsIfIgnoringDisabled() { ignoreComparator.addDriver(SAFARI); - assertTrue( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(SAFARI), CURRENT_PLATFORM_SET))); + assertThat( + ignoreComparator.shouldIgnore(ignoreForDriver(singleton(SAFARI), CURRENT_PLATFORM_SET))) + .isTrue(); } @Test void shouldIgnoreEnabledNativeEventsIfIgnoringAll() { ignoreComparator.addDriver(SAFARI); - assertTrue( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(SAFARI), CURRENT_PLATFORM_SET))); + assertThat( + ignoreComparator.shouldIgnore(ignoreForDriver(singleton(SAFARI), CURRENT_PLATFORM_SET))) + .isTrue(); } @Test void shouldIgnoreDisabledNativeEventsIfIgnoringAll() { ignoreComparator.addDriver(SAFARI); - assertTrue( - ignoreComparator.shouldIgnore( - ignoreForDriver(Collections.singleton(SAFARI), CURRENT_PLATFORM_SET))); + assertThat( + ignoreComparator.shouldIgnore(ignoreForDriver(singleton(SAFARI), CURRENT_PLATFORM_SET))) + .isTrue(); } private IgnoreList ignoreForDriver(final Set drivers, final Set platforms) { diff --git a/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java b/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java index 0045ab67ae507..795694172047f 100644 --- a/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java +++ b/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java @@ -18,10 +18,11 @@ package org.openqa.selenium.virtualauthenticator; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assumptions.assumeThat; import static org.assertj.core.api.Fail.fail; +import static org.assertj.core.api.InstanceOfAssertFactories.LIST; import static org.assertj.core.api.InstanceOfAssertFactories.MAP; -import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.MalformedURLException; import java.security.spec.PKCS8EncodedKeySpec; @@ -240,33 +241,35 @@ void testAddResidentCredential() { "getCredential([]).then(arguments[arguments.length - 1]);"); assertThat(response).asInstanceOf(MAP).containsEntry("status", "OK"); - assertThat(response).extracting("attestation.userHandle").asList().containsExactly(1L); + assertThat(response) + .extracting("attestation.userHandle") + .asInstanceOf(LIST) + .containsExactly(1L); } @Test void testAddResidentCredentialNotSupportedWhenAuthenticatorUsesU2FProtocol() { - assertThrows( - InvalidArgumentException.class, - () -> { - // Add a resident credential using the testing API. - createRKEnabledU2FAuthenticator(); - - /** A pkcs#8 encoded unencrypted EC256 private key as a base64url string. */ - String base64EncodedPK = - "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" - + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" - + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; - - PKCS8EncodedKeySpec privateKey = - new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedPK)); - - byte[] credentialId = {1, 2, 3, 4}; - byte[] userHandle = {1}; - Credential credential = - Credential.createResidentCredential( - credentialId, "localhost", privateKey, userHandle, /* signCount= */ 0); - authenticator.addCredential(credential); - }); + // Add a resident credential using the testing API. + createRKEnabledU2FAuthenticator(); + + // A pkcs#8 encoded unencrypted EC256 private key as a base64url string. + String base64EncodedPK = + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8_zMDQDYAxlU-Q" + + "hk1Dwkf0v18GZca1DMF3SaJ9HPdmShRANCAASNYX5lyVCOZLzFZzrIKmeZ2jwU" + + "RmgsJYxGP__fWN_S-j5sN4tT15XEpN_7QZnt14YvI6uvAgO0uJEboFaZlOEB"; + + PKCS8EncodedKeySpec privateKey = + new PKCS8EncodedKeySpec(Base64.getUrlDecoder().decode(base64EncodedPK)); + + byte[] credentialId = {1, 2, 3, 4}; + byte[] userHandle = {1}; + Credential credential = + Credential.createResidentCredential( + credentialId, "localhost", privateKey, userHandle, /* signCount= */ 0); + + assertThatThrownBy(() -> authenticator.addCredential(credential)) + .isInstanceOf(InvalidArgumentException.class) + .hasMessageContaining("The Authenticator does not support Resident Credentials"); } @Test