diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 789737f5836fe..655eade494358 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -9,8 +9,8 @@ - + @@ -49,8 +49,14 @@ - - + + + + + + + + @@ -305,9 +311,6 @@ - - - @@ -512,4 +515,4 @@ - \ No newline at end of file + diff --git a/.idea/modules.xml b/.idea/modules.xml index d9bc83dca0ca6..9811c78029378 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -11,4 +11,4 @@ - \ No newline at end of file + diff --git a/java/src/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMap.java b/java/src/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMap.java index 042c62ae431d8..9746000c27f1c 100644 --- a/java/src/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMap.java +++ b/java/src/org/openqa/selenium/grid/sessionmap/jdbc/JdbcBackedSessionMap.java @@ -221,7 +221,7 @@ public Session get(SessionId id) throws NoSuchSessionException { try (ResultSet sessions = statement.executeQuery()) { if (!sessions.next()) { NoSuchSessionException exception = - new NoSuchSessionException("Unable to find session."); + new NoSuchSessionException("Unable to find session with id: " + id); span.setAttribute("error", true); span.setStatus(Status.NOT_FOUND); EXCEPTION.accept(attributeMap, exception); diff --git a/java/src/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMap.java b/java/src/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMap.java index d90a2e09969ed..e1a0636f24b29 100644 --- a/java/src/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMap.java +++ b/java/src/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMap.java @@ -223,7 +223,8 @@ public URI getUri(SessionId id) throws NoSuchSessionException { attributeMap.put(REDIS_URI_KEY, uriKey); if (rawUri == null) { - NoSuchSessionException exception = new NoSuchSessionException("Unable to find session."); + NoSuchSessionException exception = + new NoSuchSessionException("Unable to find session with id: " + id); span.setAttribute("error", true); span.setStatus(Status.NOT_FOUND); EXCEPTION.accept(attributeMap, exception); diff --git a/java/test/org/openqa/selenium/ChildrenFindingTest.java b/java/test/org/openqa/selenium/ChildrenFindingTest.java index 58db7d00de0b8..80511d589b17f 100644 --- a/java/test/org/openqa/selenium/ChildrenFindingTest.java +++ b/java/test/org/openqa/selenium/ChildrenFindingTest.java @@ -42,7 +42,7 @@ void testFindingElementsOnElementByXPathShouldFindTopLevelElements() { WebElement parent = driver.findElement(By.id("multiline")); List allPs = driver.findElements(By.xpath("//p")); List children = parent.findElements(By.xpath("//p")); - assertThat(allPs.size()).isEqualTo(children.size()); + assertThat(allPs).hasSize(children.size()); } @Test diff --git a/java/test/org/openqa/selenium/CookieImplementationTest.java b/java/test/org/openqa/selenium/CookieImplementationTest.java index ec1dbe3ffd2d4..cb1a1c1b9fbac 100644 --- a/java/test/org/openqa/selenium/CookieImplementationTest.java +++ b/java/test/org/openqa/selenium/CookieImplementationTest.java @@ -119,7 +119,7 @@ public void testGetAllCookies() { openAnotherPage(); cookies = driver.manage().getCookies(); - assertThat(cookies.size()).isEqualTo(countBefore + 2); + assertThat(cookies).hasSize(countBefore + 2); assertThat(cookies.contains(one)).isTrue(); assertThat(cookies.contains(two)).isTrue(); diff --git a/java/test/org/openqa/selenium/CorrectEventFiringTest.java b/java/test/org/openqa/selenium/CorrectEventFiringTest.java index 751bf1076852c..31ace7b571c68 100644 --- a/java/test/org/openqa/selenium/CorrectEventFiringTest.java +++ b/java/test/org/openqa/selenium/CorrectEventFiringTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.openqa.selenium.WaitingConditions.elementTextToContain; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; @@ -180,11 +178,9 @@ public void testShouldFireMouseMoveEventWhenClicking() { void testShouldNotThrowIfEventHandlerThrows() { driver.get(pages.javascriptPage); - try { - driver.findElement(By.id("throwing-mouseover")).click(); - } catch (WebDriverException e) { - fail("Error in event handler should not have propagated: " + e); - } + assertThatCode(() -> driver.findElement(By.id("throwing-mouseover")).click()) + .as("Error in event handler should not have propagated") + .doesNotThrowAnyException(); } @Test @@ -410,9 +406,9 @@ public void testSendingKeysToAFocusedElementShouldNotBlurThatElement() { throw new RuntimeException(e); } } - if (!focused) { - fail("Clicking on element didn't focus it in time - can't proceed so failing"); - } + assertThat(focused) + .as("If clicking on element didn't focus it in time, we can't proceed with the test") + .isTrue(); element.sendKeys("a"); assertEventNotFired("blur", driver); diff --git a/java/test/org/openqa/selenium/ElementFindingTest.java b/java/test/org/openqa/selenium/ElementFindingTest.java index 2fd7345c4174d..190be66f829bb 100644 --- a/java/test/org/openqa/selenium/ElementFindingTest.java +++ b/java/test/org/openqa/selenium/ElementFindingTest.java @@ -708,7 +708,7 @@ void testShouldNotBeAbleToLocateByLinkTextMultipleElementsThatDoNotExist() { void testShouldBeAbleToFindMultipleElementsByPartialLinkText() { driver.get(pages.xhtmlTestPage); List elements = driver.findElements(By.partialLinkText("ick me")); - assertThat(elements.size()).isEqualTo(2); + assertThat(elements).hasSize(2); } @Test diff --git a/java/test/org/openqa/selenium/PageLoadTimeOutTest.java b/java/test/org/openqa/selenium/PageLoadTimeOutTest.java index 3b80d0c0b8e8c..4393282ed7aa4 100644 --- a/java/test/org/openqa/selenium/PageLoadTimeOutTest.java +++ b/java/test/org/openqa/selenium/PageLoadTimeOutTest.java @@ -17,14 +17,13 @@ package org.openqa.selenium; +import static java.lang.System.currentTimeMillis; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.WaitingConditions.elementTextToEqual; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; -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.SAFARI; +import static org.openqa.selenium.testing.drivers.Browser.*; import java.time.Duration; import org.junit.jupiter.api.Test; @@ -72,22 +71,16 @@ void testShouldTimeoutIfAPageTakesTooLongToLoad() { @Ignore(value = SAFARI, reason = "Flaky") public void testShouldTimeoutIfAPageTakesTooLongToLoadAfterClick() { driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(2)); - - driver.get(appServer.whereIs("page_with_link_to_slow_loading_page.html")); - WebElement link = wait.until(visibilityOfElementLocated(By.id("link-to-slow-loading-page"))); - - long start = System.currentTimeMillis(); try { - link.click(); - fail("I should have timed out"); - } catch (RuntimeException e) { - long end = System.currentTimeMillis(); + driver.get(appServer.whereIs("page_with_link_to_slow_loading_page.html")); + WebElement link = wait.until(visibilityOfElementLocated(By.id("link-to-slow-loading-page"))); - assertThat(e).isInstanceOf(TimeoutException.class); + long start = currentTimeMillis(); - int duration = (int) (end - start); - assertThat(duration).isGreaterThan(2000); - assertThat(duration).isLessThan(5000); + assertThatThrownBy(() -> link.click()).isInstanceOf(TimeoutException.class); + + long duration = currentTimeMillis() - start; + assertThat(duration).isBetween(2000L, 5000L); } finally { driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(300)); } @@ -109,18 +102,13 @@ public void testShouldTimeoutIfAPageTakesTooLongToRefresh() { driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(2)); - long start = System.currentTimeMillis(); try { - driver.navigate().refresh(); - fail("I should have timed out"); - } catch (RuntimeException e) { - long end = System.currentTimeMillis(); + long start = currentTimeMillis(); - assertThat(e).isInstanceOf(TimeoutException.class); + assertThatThrownBy(() -> driver.navigate().refresh()).isInstanceOf(TimeoutException.class); - int duration = (int) (end - start); - assertThat(duration).isGreaterThanOrEqualTo(2000); - assertThat(duration).isLessThan(4000); + long duration = currentTimeMillis() - start; + assertThat(duration).isBetween(2000L, 4000L); } finally { driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(300)); } @@ -163,19 +151,18 @@ private void testPageLoadTimeoutIsEnforced(long webDriverPageLoadTimeout) { private void assertPageLoadTimeoutIsEnforced( long webDriverPageLoadTimeout, long pageLoadTimeBuffer) { - long start = System.currentTimeMillis(); - try { - driver.get( - appServer.whereIs("sleep?time=" + (webDriverPageLoadTimeout + pageLoadTimeBuffer))); - fail("I should have timed out after " + webDriverPageLoadTimeout + " seconds"); - } catch (RuntimeException e) { - long end = System.currentTimeMillis(); - - assertThat(e).isInstanceOf(TimeoutException.class); - - long duration = end - start; - assertThat(duration).isGreaterThanOrEqualTo(webDriverPageLoadTimeout * 1000); - assertThat(duration).isLessThan((webDriverPageLoadTimeout + pageLoadTimeBuffer) * 1000); - } + long start = currentTimeMillis(); + assertThatThrownBy( + () -> { + driver.get( + appServer.whereIs( + "sleep?time=" + (webDriverPageLoadTimeout + pageLoadTimeBuffer))); + }) + .as("Should have timed out after " + webDriverPageLoadTimeout + " seconds") + .isInstanceOf(TimeoutException.class); + + long duration = currentTimeMillis() - start; + assertThat(duration).isGreaterThanOrEqualTo(webDriverPageLoadTimeout * 1000); + assertThat(duration).isLessThan((webDriverPageLoadTimeout + pageLoadTimeBuffer) * 1000); } } diff --git a/java/test/org/openqa/selenium/TakesScreenshotTest.java b/java/test/org/openqa/selenium/TakesScreenshotTest.java index 470706aea5590..454d6f9bbcf8f 100644 --- a/java/test/org/openqa/selenium/TakesScreenshotTest.java +++ b/java/test/org/openqa/selenium/TakesScreenshotTest.java @@ -18,7 +18,6 @@ package org.openqa.selenium; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt; import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs; @@ -108,7 +107,7 @@ void testGetScreenshotAsBinary() { @Test @Ignore(value = CHROME, gitHubActions = true) - public void testShouldCaptureScreenshotOfCurrentViewport() { + public void testShouldCaptureScreenshotOfCurrentViewport() throws IOException { driver.get(appServer.whereIs("screen/screen.html")); BufferedImage screenshot = getImage(); @@ -147,7 +146,7 @@ void testShouldCaptureScreenshotOfAnElement() throws Exception { @Test @Ignore(value = CHROME, gitHubActions = true) - public void testShouldCaptureScreenshotAtFramePage() { + public void testShouldCaptureScreenshotAtFramePage() throws IOException { driver.get(appServer.whereIs("screen/screen_frames.html")); wait.until(frameToBeAvailableAndSwitchToIt(By.id("frame1"))); wait.until(visibilityOfAllElementsLocatedBy(By.id("content"))); @@ -184,7 +183,7 @@ public void testShouldCaptureScreenshotAtFramePage() { @Test @Ignore(CHROME) @Ignore(EDGE) - public void testShouldCaptureScreenshotAtIFramePage() { + public void testShouldCaptureScreenshotAtIFramePage() throws IOException { driver.get(appServer.whereIs("screen/screen_iframes.html")); BufferedImage screenshot = getImage(); @@ -214,7 +213,7 @@ public void testShouldCaptureScreenshotAtIFramePage() { @Test @Ignore(FIREFOX) @Ignore(value = CHROME, gitHubActions = true) - public void testShouldCaptureScreenshotAtFramePageAfterSwitching() { + public void testShouldCaptureScreenshotAtFramePageAfterSwitching() throws IOException { driver.get(appServer.whereIs("screen/screen_frames.html")); driver.switchTo().frame(driver.findElement(By.id("frame2"))); @@ -248,7 +247,7 @@ public void testShouldCaptureScreenshotAtFramePageAfterSwitching() { @Ignore(CHROME) @Ignore(EDGE) @Ignore(FIREFOX) - public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() { + public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() throws IOException { driver.get(appServer.whereIs("screen/screen_iframes.html")); driver.switchTo().frame(driver.findElement(By.id("iframe2"))); @@ -272,7 +271,7 @@ public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() { /* grid X size */ 6, /* grid Y size */ 6)); - // expectation is that screenshot at page with Iframes after switching to a Iframe + // expectation is that screenshot at page with Iframes after switching to iframe // will be taken for full page compareColors(expectedColors, actualColors); } @@ -282,17 +281,12 @@ public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() { * * @return Image object */ - private BufferedImage getImage() { - BufferedImage image = null; - try { - byte[] imageData = screenshooter.getScreenshotAs(OutputType.BYTES); - assertThat(imageData).isNotNull(); - assertThat(imageData.length).isPositive(); - image = ImageIO.read(new ByteArrayInputStream(imageData)); - assertThat(image).isNotNull(); - } catch (IOException e) { - fail("Image screenshot file is invalid: " + e.getMessage()); - } + private BufferedImage getImage() throws IOException { + byte[] imageData = screenshooter.getScreenshotAs(OutputType.BYTES); + assertThat(imageData).isNotNull(); + assertThat(imageData.length).isPositive(); + BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData)); + assertThat(image).isNotNull(); // saveImageToTmpFile(image); return image; @@ -337,28 +331,23 @@ private Set generateExpectedColors( private Set scanActualColors(BufferedImage image, final int stepX, final int stepY) { Set colors = new TreeSet<>(); - try { - int height = image.getHeight(); - int width = image.getWidth(); - assertThat(width > 0).isTrue(); - assertThat(height > 0).isTrue(); - - Raster raster = image.getRaster(); - for (int i = 0; i < width; i = i + stepX) { - for (int j = 0; j < height; j = j + stepY) { - String hex = - String.format( - "#%02x%02x%02x", - (raster.getSample(i, j, 0)), - (raster.getSample(i, j, 1)), - (raster.getSample(i, j, 2))); - colors.add(hex); - } + int height = image.getHeight(); + int width = image.getWidth(); + assertThat(width > 0).isTrue(); + assertThat(height > 0).isTrue(); + + Raster raster = image.getRaster(); + for (int i = 0; i < width; i = i + stepX) { + for (int j = 0; j < height; j = j + stepY) { + String hex = + String.format( + "#%02x%02x%02x", + (raster.getSample(i, j, 0)), + (raster.getSample(i, j, 1)), + (raster.getSample(i, j, 2))); + colors.add(hex); } - } catch (Exception e) { - fail("Unable to get actual colors from screenshot: " + e.getMessage()); } - assertThat(colors).isNotEmpty(); return colors; @@ -379,17 +368,7 @@ private void compareColors(Set expectedColors, Set actualColors) cleanActualColors.remove("#000000"); cleanActualColors.remove("#ffffff"); - if (!expectedColors.containsAll(cleanActualColors)) { - fail( - "There are unexpected colors on the screenshot: " - + Sets.difference(cleanActualColors, expectedColors)); - } - - if (!cleanActualColors.containsAll(expectedColors)) { - fail( - "There are expected colors not present on the screenshot: " - + Sets.difference(expectedColors, cleanActualColors)); - } + assertThat(cleanActualColors).containsExactlyInAnyOrderElementsOf(expectedColors); } private boolean onlyBlack(Set colors) { @@ -406,13 +385,8 @@ private boolean onlyWhite(Set colors) { * @param im image */ @SuppressWarnings("unused") - private void saveImageToTmpFile(String testMethodName, BufferedImage im) { - + private void saveImageToTmpFile(String testMethodName, BufferedImage im) throws IOException { File outputfile = new File(testMethodName + "_image.png"); - try { - ImageIO.write(im, "png", outputfile); - } catch (IOException e) { - fail("Unable to write image to file: " + e.getMessage()); - } + ImageIO.write(im, "png", outputfile); } } diff --git a/java/test/org/openqa/selenium/WebNetworkTest.java b/java/test/org/openqa/selenium/WebNetworkTest.java index 1b50a28e348da..49a6c74229349 100644 --- a/java/test/org/openqa/selenium/WebNetworkTest.java +++ b/java/test/org/openqa/selenium/WebNetworkTest.java @@ -17,9 +17,9 @@ package org.openqa.selenium; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.openqa.selenium.remote.http.Contents.utf8String; import java.net.URI; diff --git a/java/test/org/openqa/selenium/WebScriptExecuteTest.java b/java/test/org/openqa/selenium/WebScriptExecuteTest.java index 35500086ce69c..9138b2774c549 100644 --- a/java/test/org/openqa/selenium/WebScriptExecuteTest.java +++ b/java/test/org/openqa/selenium/WebScriptExecuteTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.time.Instant; @@ -85,7 +85,7 @@ void canExecuteScriptWithMinusZeroArgument() { "-0"); assertThat(value.getType()).isEqualTo("number"); - assertThat(value.getValue().get()).isEqualTo("-0"); + assertThat(value.getValue()).hasValue("-0"); } @Test @@ -103,7 +103,7 @@ void canExecuteScriptWithInfinityArgument() { "Infinity"); assertThat(value.getType()).isEqualTo("number"); - assertThat(value.getValue().get()).isEqualTo("Infinity"); + assertThat(value.getValue()).hasValue("Infinity"); } @Test @@ -121,7 +121,7 @@ void canExecuteScriptWithMinusInfinityArgument() { "-Infinity"); assertThat(value.getType()).isEqualTo("number"); - assertThat(value.getValue().get()).isEqualTo("-Infinity"); + assertThat(value.getValue()).hasValue("-Infinity"); } @Test @@ -138,7 +138,7 @@ void canExecuteScriptWithNumberArgument() { 1.4); assertThat(value.getType()).isEqualTo("number"); - assertThat(value.getValue().get()).isEqualTo(1.4); + assertThat(value.getValue()).hasValue(1.4); } @Test @@ -155,7 +155,7 @@ void canExecuteScriptWithIntegerArgument() { 1); assertThat(value.getType()).isEqualTo("number"); - assertThat(value.getValue().get()).isEqualTo(1L); + assertThat(value.getValue()).hasValue(1L); } @Test @@ -172,7 +172,7 @@ void canExecuteScriptWithBooleanArgument() { true); assertThat(value.getType()).isEqualTo("boolean"); - assertThat(value.getValue().get()).isEqualTo(true); + assertThat(value.getValue()).hasValue(true); } @Test @@ -189,7 +189,7 @@ void canExecuteScriptWithBigIntArgument() { BigInteger.valueOf(42L)); assertThat(value.getType()).isEqualTo("bigint"); - assertThat(value.getValue().get()).isEqualTo("42"); + assertThat(value.getValue()).hasValue("42"); } @Test @@ -212,7 +212,7 @@ void canExecuteScriptWithArrayArgument() { assertThat(value.getType()).isEqualTo("array"); List values = (List) value.getValue().get(); - assertThat(values.size()).isEqualTo(2); + assertThat(values).hasSize(2); } @Test @@ -235,7 +235,7 @@ void canExecuteScriptWithSetArgument() { assertThat(value.getType()).isEqualTo("set"); List values = (List) value.getValue().get(); - assertThat(values.size()).isEqualTo(2); + assertThat(values).hasSize(2); } @Test @@ -276,7 +276,7 @@ void canExecuteScriptWithMapArgument() { assertThat(value.getType()).isEqualTo("map"); Map values = (Map) value.getValue().get(); - assertThat(values.size()).isEqualTo(2); + assertThat(values).hasSize(2); } @Test @@ -299,7 +299,7 @@ void canExecuteScriptWithObjectArgument() { assertThat(value.getType()).isEqualTo("object"); Map values = (Map) value.getValue().get(); - assertThat(values.size()).isEqualTo(6); + assertThat(values).hasSize(6); } @Test diff --git a/java/test/org/openqa/selenium/WebScriptTest.java b/java/test/org/openqa/selenium/WebScriptTest.java index 29522eb060e9c..87febcaa75347 100644 --- a/java/test/org/openqa/selenium/WebScriptTest.java +++ b/java/test/org/openqa/selenium/WebScriptTest.java @@ -18,8 +18,7 @@ package org.openqa.selenium; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.fail; +import static org.assertj.core.api.Assertions.*; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; import java.time.Duration; @@ -57,7 +56,7 @@ void canAddConsoleMessageHandler() ConsoleLogEntry logEntry = future.get(5, TimeUnit.SECONDS); assertThat(logEntry.getText()).isEqualTo("Hello, world!"); - assertThat(logEntry.getArgs().size()).isEqualTo(1); + assertThat(logEntry.getArgs()).hasSize(1); assertThat(logEntry.getArgs().get(0).getType()).isEqualTo("string"); assertThat(logEntry.getType()).isEqualTo("console"); assertThat(logEntry.getLevel()).isEqualTo(LogLevel.INFO); @@ -90,12 +89,10 @@ void canRemoveConsoleMessageHandler() ConsoleLogEntry logEntry = future1.get(5, TimeUnit.SECONDS); assertThat(logEntry.getText()).isEqualTo("Hello, world!"); - try { - future2.get(5, TimeUnit.SECONDS); - fail("Should be able to read the console messages"); - } catch (TimeoutException e) { - assertThat(e).isNotNull(); - } + assertThatThrownBy(() -> future2.get(5, TimeUnit.SECONDS)) + .as("Should be able to read the console messages") + .isInstanceOf(TimeoutException.class); + ((RemoteWebDriver) driver).script().removeConsoleMessageHandler(id1); } @@ -144,12 +141,9 @@ void canRemoveJsErrorHandler() throws ExecutionException, InterruptedException, assertThat(logEntry.getType()).isEqualTo("javascript"); assertThat(logEntry.getLevel()).isEqualTo(LogLevel.ERROR); - try { - future2.get(5, TimeUnit.SECONDS); - fail("Should be able to read the JS errors"); - } catch (TimeoutException e) { - assertThat(e).isNotNull(); - } + assertThatThrownBy(() -> future2.get(5, TimeUnit.SECONDS)) + .as("Should be able to read the JS errors") + .isInstanceOf(TimeoutException.class); ((RemoteWebDriver) driver).script().removeConsoleMessageHandler(id1); } @@ -259,7 +253,7 @@ void canPinScript() throws ExecutionException, InterruptedException, TimeoutExce @Test @NeedsFreshDriver - void canUnpinScript() throws ExecutionException, InterruptedException, TimeoutException { + void canUnpinScript() { CountDownLatch latch = new CountDownLatch(2); String pinnedScript = diff --git a/java/test/org/openqa/selenium/bidi/BiDiSessionCleanUpTest.java b/java/test/org/openqa/selenium/bidi/BiDiSessionCleanUpTest.java index 71b48a16f2cd3..b51d99893890b 100644 --- a/java/test/org/openqa/selenium/bidi/BiDiSessionCleanUpTest.java +++ b/java/test/org/openqa/selenium/bidi/BiDiSessionCleanUpTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium.bidi; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.junit.jupiter.api.Test; import org.openqa.selenium.WebDriverException; diff --git a/java/test/org/openqa/selenium/bidi/BiDiSessionTest.java b/java/test/org/openqa/selenium/bidi/BiDiSessionTest.java index 9524ae06ab698..31cb3e6ca9663 100644 --- a/java/test/org/openqa/selenium/bidi/BiDiSessionTest.java +++ b/java/test/org/openqa/selenium/bidi/BiDiSessionTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.openqa.selenium.testing.JupiterTestBase; diff --git a/java/test/org/openqa/selenium/bidi/BiDiTest.java b/java/test/org/openqa/selenium/bidi/BiDiTest.java index 26212c80eefcd..ea050841b1713 100644 --- a/java/test/org/openqa/selenium/bidi/BiDiTest.java +++ b/java/test/org/openqa/selenium/bidi/BiDiTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.drivers.Browser.EDGE; import java.util.concurrent.CompletableFuture; diff --git a/java/test/org/openqa/selenium/bidi/browsingcontext/BrowsingContextInspectorTest.java b/java/test/org/openqa/selenium/bidi/browsingcontext/BrowsingContextInspectorTest.java index faec1ae0aba22..1d6f6afb3bab4 100644 --- a/java/test/org/openqa/selenium/bidi/browsingcontext/BrowsingContextInspectorTest.java +++ b/java/test/org/openqa/selenium/bidi/browsingcontext/BrowsingContextInspectorTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium.bidi.browsingcontext; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.openqa.selenium.testing.drivers.Browser.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; import java.util.List; import java.util.Optional; @@ -213,7 +213,7 @@ void canListenToUserPromptClosedEvent() UserPromptClosed userPromptClosed = future.get(5, TimeUnit.SECONDS); assertThat(userPromptClosed.getBrowsingContextId()).isEqualTo(context.getId()); assertThat(userPromptClosed.getUserText().isPresent()).isTrue(); - assertThat(userPromptClosed.getUserText().get()).isEqualTo("selenium"); + assertThat(userPromptClosed.getUserText()).hasValue("selenium"); assertThat(userPromptClosed.getAccepted()).isTrue(); } } diff --git a/java/test/org/openqa/selenium/bidi/browsingcontext/LocateNodesTest.java b/java/test/org/openqa/selenium/bidi/browsingcontext/LocateNodesTest.java index 611f3c18ba086..c92026625aa90 100644 --- a/java/test/org/openqa/selenium/bidi/browsingcontext/LocateNodesTest.java +++ b/java/test/org/openqa/selenium/bidi/browsingcontext/LocateNodesTest.java @@ -16,8 +16,8 @@ // under the License. package org.openqa.selenium.bidi.browsingcontext; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.openqa.selenium.testing.drivers.Browser.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; import java.util.ArrayList; import java.util.List; @@ -49,7 +49,7 @@ void canLocateNodes() { LocateNodeParameters parameters = new LocateNodeParameters(Locator.css("div")); List elements = browsingContext.locateNodes(parameters); - assertThat(elements.size()).isEqualTo(13); + assertThat(elements).hasSize(13); } @Test @@ -61,7 +61,7 @@ void canLocateNodesWithJustLocator() { driver.get(pages.xhtmlTestPage); List elements = browsingContext.locateNodes(Locator.css("div")); - assertThat(elements.size()).isEqualTo(13); + assertThat(elements).hasSize(13); } @Test @@ -94,8 +94,8 @@ void canLocateNodesWithCSSLocator() { assertThat(value.getType()).isEqualTo("node"); assertThat(value.getValue().isPresent()).isTrue(); NodeProperties properties = (NodeProperties) value.getValue().get(); - assertThat(properties.getLocalName().get()).isEqualTo("div"); - assertThat(properties.getAttributes().get().size()).isEqualTo(1); + assertThat(properties.getLocalName()).hasValue("div"); + assertThat(properties.getAttributes().get()).hasSize(1); assertThat(properties.getAttributes().get().get("class")).isEqualTo("content"); } @@ -117,8 +117,8 @@ void canLocateNodesWithXPathLocator() { assertThat(value.getType()).isEqualTo("node"); assertThat(value.getValue().isPresent()).isTrue(); NodeProperties properties = (NodeProperties) value.getValue().get(); - assertThat(properties.getLocalName().get()).isEqualTo("div"); - assertThat(properties.getAttributes().get().size()).isEqualTo(1); + assertThat(properties.getLocalName()).hasValue("div"); + assertThat(properties.getAttributes().get()).hasSize(1); assertThat(properties.getAttributes().get().get("class")).isEqualTo("content"); } @@ -154,7 +154,7 @@ void canLocateNodesWithMaxNodeCount() { new LocateNodeParameters(Locator.css("div")).setMaxNodeCount(4); List elements = browsingContext.locateNodes(parameters); - assertThat(elements.size()).isEqualTo(4); + assertThat(elements).hasSize(4); } @Test @@ -193,7 +193,7 @@ void canLocateNodesGivenStartNodes() { .setMaxNodeCount(50); List elements = browsingContext.locateNodes(parameters); - assertThat(elements.size()).isEqualTo(35); + assertThat(elements).hasSize(35); } @Test @@ -209,7 +209,7 @@ void canLocateNodesInAGivenSandbox() { new LocateNodeParameters(Locator.css("div")).setSandbox(sandbox).setMaxNodeCount(1); List elements = browsingContext.locateNodes(parameters); - assertThat(elements.size()).isEqualTo(1); + assertThat(elements).hasSize(1); String nodeId = elements.get(0).getSharedId().get(); diff --git a/java/test/org/openqa/selenium/bidi/emulation/SetGeolocationOverrideTest.java b/java/test/org/openqa/selenium/bidi/emulation/SetGeolocationOverrideTest.java index c7d3be51ac596..0b5ce769285a6 100644 --- a/java/test/org/openqa/selenium/bidi/emulation/SetGeolocationOverrideTest.java +++ b/java/test/org/openqa/selenium/bidi/emulation/SetGeolocationOverrideTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium.bidi.emulation; import static java.lang.Math.abs; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; import java.util.List; diff --git a/java/test/org/openqa/selenium/bidi/emulation/SetScriptingEnabledTest.java b/java/test/org/openqa/selenium/bidi/emulation/SetScriptingEnabledTest.java index bab80ad0fb4d3..a3c6440504ca8 100644 --- a/java/test/org/openqa/selenium/bidi/emulation/SetScriptingEnabledTest.java +++ b/java/test/org/openqa/selenium/bidi/emulation/SetScriptingEnabledTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi.emulation; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; import java.util.List; diff --git a/java/test/org/openqa/selenium/bidi/emulation/SetTimezoneOverrideTest.java b/java/test/org/openqa/selenium/bidi/emulation/SetTimezoneOverrideTest.java index 73dc7ab1913f4..2c40b9ad809a8 100644 --- a/java/test/org/openqa/selenium/bidi/emulation/SetTimezoneOverrideTest.java +++ b/java/test/org/openqa/selenium/bidi/emulation/SetTimezoneOverrideTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi.emulation; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; import java.time.ZoneId; diff --git a/java/test/org/openqa/selenium/bidi/input/DragAndDropTest.java b/java/test/org/openqa/selenium/bidi/input/DragAndDropTest.java index e3feec87032cf..0b3de4c7da413 100644 --- a/java/test/org/openqa/selenium/bidi/input/DragAndDropTest.java +++ b/java/test/org/openqa/selenium/bidi/input/DragAndDropTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium.bidi.input; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.WaitingConditions.elementLocationToBe; import static org.openqa.selenium.testing.drivers.Browser.CHROME; import static org.openqa.selenium.testing.drivers.Browser.EDGE; @@ -140,19 +140,21 @@ void testDragTooFar() { driver.get(pages.dragAndDropPage); Actions actions = new Actions(driver); - try { - WebElement img = driver.findElement(By.id("test1")); - - // Attempt to drag the image outside of the bounds of the page. + WebElement img = driver.findElement(By.id("test1")); - inputModule.perform( - windowHandle, - actions.dragAndDropBy(img, Integer.MAX_VALUE, Integer.MAX_VALUE).getSequences()); - fail("These coordinates are outside the page - expected to fail."); - } catch (BiDiException expected) { - // Release mouse button - move was interrupted in the middle. - inputModule.perform(windowHandle, new Actions(driver).release().getSequences()); - } + assertThatThrownBy( + () -> + inputModule.perform( + windowHandle, + actions + .dragAndDropBy(img, Integer.MAX_VALUE, Integer.MAX_VALUE) + .getSequences())) + .as("These coordinates are outside the page - expected to fail.") + .isInstanceOf(BiDiException.class) + .hasMessageContaining("Move target (2147483664, 2147483664) is out of bounds"); + + // Release mouse button - move was interrupted in the middle. + inputModule.perform(windowHandle, new Actions(driver).release().getSequences()); } @NoDriverAfterTest diff --git a/java/test/org/openqa/selenium/bidi/log/LogInspectorTest.java b/java/test/org/openqa/selenium/bidi/log/LogInspectorTest.java index 65da3f19105a3..671634c04ae7f 100644 --- a/java/test/org/openqa/selenium/bidi/log/LogInspectorTest.java +++ b/java/test/org/openqa/selenium/bidi/log/LogInspectorTest.java @@ -19,7 +19,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; import java.util.HashSet; import java.util.Set; @@ -57,7 +56,7 @@ void canListenToConsoleLog() throws ExecutionException, InterruptedException, Ti assertThat(source.getBrowsingContext().isPresent()).isTrue(); assertThat(source.getRealm()).isNotNull(); assertThat(logEntry.getText()).isEqualTo("Hello, world!"); - assertThat(logEntry.getArgs().size()).isEqualTo(1); + assertThat(logEntry.getArgs()).hasSize(1); assertThat(logEntry.getArgs().get(0).getType()).isEqualTo("string"); assertThat(logEntry.getType()).isEqualTo("console"); assertThat(logEntry.getLevel()).isEqualTo(LogLevel.INFO); @@ -79,25 +78,25 @@ void canFilterConsoleLogs() throws ExecutionException, InterruptedException, Tim ConsoleLogEntry logEntry = future.get(5, TimeUnit.SECONDS); assertThat(logEntry.getText()).isEqualTo("Hello, world!"); - assertThat(logEntry.getArgs().size()).isEqualTo(1); + assertThat(logEntry.getArgs()).hasSize(1); assertThat(logEntry.getType()).isEqualTo("console"); assertThat(logEntry.getLevel()).isEqualTo(LogLevel.INFO); assertThat(logEntry.getMethod()).isEqualTo("log"); - CompletableFuture errorLogfuture = new CompletableFuture<>(); + CompletableFuture errorLogFuture = new CompletableFuture<>(); - logInspector.onConsoleEntry(errorLogfuture::complete, FilterBy.logLevel(LogLevel.ERROR)); + logInspector.onConsoleEntry(errorLogFuture::complete, FilterBy.logLevel(LogLevel.ERROR)); driver.findElement(By.id("consoleError")).click(); - ConsoleLogEntry errorLogEntry = errorLogfuture.get(5, TimeUnit.SECONDS); + ConsoleLogEntry errorLogEntry = errorLogFuture.get(5, TimeUnit.SECONDS); assertThat(errorLogEntry.getText()).isEqualTo("I am console error"); - assertThat(errorLogEntry.getArgs().size()).isEqualTo(1); + assertThat(errorLogEntry.getArgs()).hasSize(1); assertThat(errorLogEntry.getType()).isEqualTo("console"); assertThat(errorLogEntry.getLevel()).isEqualTo(LogLevel.ERROR); assertThat(errorLogEntry.getMethod()).isEqualTo("error"); assertThat(errorLogEntry.getStackTrace()).isNotNull(); - assertThat(errorLogEntry.getStackTrace().getCallFrames().size()).isEqualTo(2); + assertThat(errorLogEntry.getStackTrace().getCallFrames()).hasSize(2); } } @@ -127,7 +126,7 @@ void canListenToJavascriptLog() @Test @NeedsFreshDriver - void canFilterJavascriptLogs() throws ExecutionException, InterruptedException { + void canFilterJavascriptLogs() throws ExecutionException, InterruptedException, TimeoutException { try (LogInspector logInspector = new LogInspector(driver)) { CompletableFuture future = new CompletableFuture<>(); logInspector.onJavaScriptLog(future::complete, FilterBy.logLevel(LogLevel.ERROR)); @@ -136,12 +135,7 @@ void canFilterJavascriptLogs() throws ExecutionException, InterruptedException { driver.get(page); driver.findElement(By.id("jsException")).click(); - JavascriptLogEntry logEntry = null; - try { - logEntry = future.get(5, TimeUnit.SECONDS); - } catch (TimeoutException e) { - fail("Time out exception" + e.getMessage()); - } + JavascriptLogEntry logEntry = future.get(5, TimeUnit.SECONDS); assertThat(logEntry.getText()).isEqualTo("Error: Not working"); assertThat(logEntry.getType()).isEqualTo("javascript"); @@ -198,7 +192,7 @@ void canRetrieveStacktraceForALog() @Test @NeedsFreshDriver - void canFilterLogs() throws ExecutionException, InterruptedException { + void canFilterLogs() throws ExecutionException, InterruptedException, TimeoutException { try (LogInspector logInspector = new LogInspector(driver)) { CompletableFuture future = new CompletableFuture<>(); logInspector.onLog(future::complete, FilterBy.logLevel(LogLevel.INFO)); @@ -207,18 +201,13 @@ void canFilterLogs() throws ExecutionException, InterruptedException { driver.get(page); driver.findElement(By.id("consoleLog")).click(); - LogEntry logEntry = null; - try { - logEntry = future.get(5, TimeUnit.SECONDS); - } catch (TimeoutException e) { - fail("Time out exception" + e.getMessage()); - } + LogEntry logEntry = future.get(5, TimeUnit.SECONDS); assertThat(logEntry.getConsoleLogEntry().isPresent()).isTrue(); ConsoleLogEntry consoleLogEntry = logEntry.getConsoleLogEntry().get(); assertThat(consoleLogEntry.getText()).isEqualTo("Hello, world!"); - assertThat(consoleLogEntry.getArgs().size()).isEqualTo(1); + assertThat(consoleLogEntry.getArgs()).hasSize(1); assertThat(consoleLogEntry.getType()).isEqualTo("console"); assertThat(consoleLogEntry.getLevel()).isEqualTo(LogLevel.INFO); assertThat(consoleLogEntry.getMethod()).isEqualTo("log"); @@ -243,7 +232,7 @@ void canListenToConsoleLogForABrowsingContext() ConsoleLogEntry logEntry = future.get(5, TimeUnit.SECONDS); assertThat(logEntry.getText()).isEqualTo("Hello, world!"); - assertThat(logEntry.getArgs().size()).isEqualTo(1); + assertThat(logEntry.getArgs()).hasSize(1); assertThat(logEntry.getType()).isEqualTo("console"); assertThat(logEntry.getLevel()).isEqualTo(LogLevel.INFO); assertThat(logEntry.getMethod()).isEqualTo("log"); @@ -299,8 +288,7 @@ void canListenToJavascriptErrorLogForABrowsingContext() @Disabled("Until browsers support subscribing to multiple contexts.") @Test @NeedsFreshDriver - void canListenToConsoleLogForMultipleBrowsingContexts() - throws ExecutionException, InterruptedException, TimeoutException { + void canListenToConsoleLogForMultipleBrowsingContexts() throws InterruptedException { page = appServer.whereIs("/bidi/logEntryAdded.html"); String firstBrowsingContextId = driver.getWindowHandle(); String secondBrowsingContextId = driver.switchTo().newWindow(WindowType.TAB).getWindowHandle(); diff --git a/java/test/org/openqa/selenium/bidi/network/AddInterceptParametersTest.java b/java/test/org/openqa/selenium/bidi/network/AddInterceptParametersTest.java index 27bf43639420f..9d1fa42dda437 100644 --- a/java/test/org/openqa/selenium/bidi/network/AddInterceptParametersTest.java +++ b/java/test/org/openqa/selenium/bidi/network/AddInterceptParametersTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi.network; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.jupiter.api.Test; diff --git a/java/test/org/openqa/selenium/bidi/network/NetworkCommandsTest.java b/java/test/org/openqa/selenium/bidi/network/NetworkCommandsTest.java index b6347925cd67e..c7d4c6b71c4bc 100644 --- a/java/test/org/openqa/selenium/bidi/network/NetworkCommandsTest.java +++ b/java/test/org/openqa/selenium/bidi/network/NetworkCommandsTest.java @@ -17,9 +17,9 @@ package org.openqa.selenium.bidi.network; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.openqa.selenium.bidi.browsingcontext.ReadinessState.COMPLETE; import static org.openqa.selenium.testing.drivers.Browser.*; import java.time.Duration; @@ -28,6 +28,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.logging.Logger; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; @@ -36,13 +38,14 @@ import org.openqa.selenium.WindowType; import org.openqa.selenium.bidi.BiDiException; import org.openqa.selenium.bidi.browsingcontext.BrowsingContext; -import org.openqa.selenium.bidi.browsingcontext.ReadinessState; import org.openqa.selenium.bidi.module.Network; import org.openqa.selenium.testing.JupiterTestBase; import org.openqa.selenium.testing.NeedsFreshDriver; import org.openqa.selenium.testing.NotYetImplemented; class NetworkCommandsTest extends JupiterTestBase { + private static final Logger LOG = Logger.getLogger(NetworkCommandsTest.class.getName()); + private String page; @Test @@ -82,8 +85,7 @@ void canContinueRequest() throws InterruptedException { BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - browsingContext.navigate( - appServer.whereIs("/bidi/logEntryAdded.html"), ReadinessState.COMPLETE); + browsingContext.navigate(appServer.whereIs("/bidi/logEntryAdded.html"), COMPLETE); boolean countdown = latch.await(5, TimeUnit.SECONDS); assertThat(countdown).isTrue(); } @@ -111,8 +113,7 @@ void canContinueResponse() throws InterruptedException { BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - browsingContext.navigate( - appServer.whereIs("/bidi/logEntryAdded.html"), ReadinessState.COMPLETE); + browsingContext.navigate(appServer.whereIs("/bidi/logEntryAdded.html"), COMPLETE); boolean countdown = latch.await(5, TimeUnit.SECONDS); assertThat(countdown).isTrue(); @@ -140,8 +141,7 @@ void canProvideResponse() throws InterruptedException { BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - browsingContext.navigate( - appServer.whereIs("/bidi/logEntryAdded.html"), ReadinessState.COMPLETE); + browsingContext.navigate(appServer.whereIs("/bidi/logEntryAdded.html"), COMPLETE); boolean countdown = latch.await(5, TimeUnit.SECONDS); assertThat(countdown).isTrue(); @@ -176,8 +176,7 @@ void canProvideResponseWithAllParameters() throws InterruptedException { BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - browsingContext.navigate( - appServer.whereIs("/bidi/logEntryAdded.html"), ReadinessState.COMPLETE); + browsingContext.navigate(appServer.whereIs("/bidi/logEntryAdded.html"), COMPLETE); boolean countdown = latch.await(5, TimeUnit.SECONDS); assertThat(countdown).isTrue(); @@ -212,7 +211,7 @@ void canContinueWithAuthCredentials() { page = appServer.whereIs("basicAuth"); BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - browsingContext.navigate(page, ReadinessState.COMPLETE); + browsingContext.navigate(page, COMPLETE); assertThat(driver.findElement(By.tagName("h1")).getText()).isEqualTo("authorized"); } @@ -232,12 +231,8 @@ void canContinueWithoutAuthCredentials() { page = appServer.whereIs("basicAuth"); BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - try { - browsingContext.navigate(page, ReadinessState.COMPLETE); - fail("Exception should be thrown"); - } catch (Exception e) { - assertThat(e).isInstanceOf(WebDriverException.class); - } + assertThatThrownBy(() -> browsingContext.navigate(page, COMPLETE)) + .isInstanceOf(WebDriverException.class); } } @@ -269,15 +264,17 @@ void canCancelAuth() throws InterruptedException { BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); try { - browsingContext.navigate(page, ReadinessState.COMPLETE); - } catch (Exception BiDiException) { - // Ignore - // Only Chromium browsers throw an error because the navigation did not complete as - // expected. + browsingContext.navigate(page, COMPLETE); + } catch (BiDiException expectedForChrome) { + LOG.log( + Level.FINE, + "Expected exception for chrome because because the navigation " + + "did not complete as expected: {0}", + expectedForChrome.toString()); } latch.await(10, TimeUnit.SECONDS); - assertThat(status.get()).isEqualTo(401); + assertThat(status).hasValue(401); } } @@ -295,8 +292,7 @@ void canFailRequest() { () -> { BrowsingContext browsingContext = new BrowsingContext(driver, driver.getWindowHandle()); - browsingContext.navigate( - appServer.whereIs("/bidi/logEntryAdded.html"), ReadinessState.COMPLETE); + browsingContext.navigate(appServer.whereIs("/bidi/logEntryAdded.html"), COMPLETE); }) .isInstanceOf(WebDriverException.class); } diff --git a/java/test/org/openqa/selenium/bidi/network/NetworkEventsTest.java b/java/test/org/openqa/selenium/bidi/network/NetworkEventsTest.java index c3af6af482b53..ac7485e8beec8 100644 --- a/java/test/org/openqa/selenium/bidi/network/NetworkEventsTest.java +++ b/java/test/org/openqa/selenium/bidi/network/NetworkEventsTest.java @@ -17,8 +17,9 @@ package org.openqa.selenium.bidi.network; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.openqa.selenium.testing.drivers.Browser.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.testing.drivers.Browser.CHROME; +import static org.openqa.selenium.testing.drivers.Browser.EDGE; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -116,7 +117,7 @@ void canListenToResponseCompletedEventWithCookie() BeforeRequestSent requestSent = future.get(5, TimeUnit.SECONDS); String windowHandle = driver.getWindowHandle(); assertThat(requestSent.getBrowsingContextId()).isEqualTo(windowHandle); - assertThat(requestSent.getRequest().getCookies().size()).isEqualTo(1); + assertThat(requestSent.getRequest().getCookies()).hasSize(1); assertThat(requestSent.getRequest().getCookies().get(0).getName()).isEqualTo("foo"); assertThat(requestSent.getRequest().getCookies().get(0).getValue().getValue()) .isEqualTo("bar"); diff --git a/java/test/org/openqa/selenium/bidi/script/CallFunctionParameterTest.java b/java/test/org/openqa/selenium/bidi/script/CallFunctionParameterTest.java index b03770358cf0a..914f76ec38e10 100644 --- a/java/test/org/openqa/selenium/bidi/script/CallFunctionParameterTest.java +++ b/java/test/org/openqa/selenium/bidi/script/CallFunctionParameterTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi.script; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.testing.drivers.Browser.IE; import static org.openqa.selenium.testing.drivers.Browser.SAFARI; @@ -133,7 +133,7 @@ void canCallFunctionWithArguments() { EvaluateResultSuccess successResult = (EvaluateResultSuccess) result; assertThat(successResult.getResult().getType()).isEqualTo("array"); assertThat(successResult.getResult().getValue().isPresent()).isTrue(); - assertThat(((List) successResult.getResult().getValue().get()).size()).isEqualTo(2); + assertThat(((List) successResult.getResult().getValue().get())).hasSize(2); } } @@ -339,8 +339,7 @@ void canCallFunctionThatThrowsException() { assertThat(exception.getExceptionDetails().getText()).contains("SyntaxError:"); assertThat(exception.getExceptionDetails().getLineNumber()).isPositive(); assertThat(exception.getExceptionDetails().getColumnNumber()).isPositive(); - assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames().size()) - .isEqualTo(0); + assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames()).hasSize(0); } } diff --git a/java/test/org/openqa/selenium/bidi/script/EvaluateParametersTest.java b/java/test/org/openqa/selenium/bidi/script/EvaluateParametersTest.java index 98e3bfd77ef6e..686c2be3a9257 100644 --- a/java/test/org/openqa/selenium/bidi/script/EvaluateParametersTest.java +++ b/java/test/org/openqa/selenium/bidi/script/EvaluateParametersTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi.script; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Optional; @@ -119,8 +119,7 @@ void canEvaluateScriptThatThrowsException() { assertThat(exception.getExceptionDetails().getException().getType()).isEqualTo("error"); assertThat(exception.getExceptionDetails().getText()).contains("SyntaxError:"); assertThat(exception.getExceptionDetails().getLineNumber()).isGreaterThanOrEqualTo(0); - assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames().size()) - .isEqualTo(0); + assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames()).hasSize(0); } } diff --git a/java/test/org/openqa/selenium/bidi/script/LocalValueTest.java b/java/test/org/openqa/selenium/bidi/script/LocalValueTest.java index cd8c512613a38..14fce31c5e47d 100644 --- a/java/test/org/openqa/selenium/bidi/script/LocalValueTest.java +++ b/java/test/org/openqa/selenium/bidi/script/LocalValueTest.java @@ -17,7 +17,7 @@ package org.openqa.selenium.bidi.script; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.HashMap; @@ -319,7 +319,7 @@ void canCallFunctionWithArrayArgument() { assertThat(successResult.getResult().getType()).isEqualTo("array"); assertThat(successResult.getResult().getValue().isPresent()).isTrue(); List resultValue = (List) successResult.getResult().getValue().get(); - assertThat(resultValue.size()).isEqualTo(1); + assertThat(resultValue).hasSize(1); assertThat(resultValue.get(0).getType()).isEqualTo("string"); assertThat((String) resultValue.get(0).getValue().get()).isEqualTo("foobar"); } @@ -357,7 +357,7 @@ void canCallFunctionWithSetArgument() { assertThat(successResult.getResult().getType()).isEqualTo("set"); assertThat(successResult.getResult().getValue().isPresent()).isTrue(); List resultValue = (List) successResult.getResult().getValue().get(); - assertThat(resultValue.size()).isEqualTo(1); + assertThat(resultValue).hasSize(1); assertThat(resultValue.get(0).getType()).isEqualTo("string"); assertThat((String) resultValue.get(0).getValue().get()).isEqualTo("foobar"); } @@ -392,7 +392,7 @@ void canCallFunctionWithDateArgument() { EvaluateResultSuccess successResult = (EvaluateResultSuccess) result; assertThat(successResult.getResult().getType()).isEqualTo("date"); assertThat(successResult.getResult().getValue().isPresent()).isTrue(); - assertThat(successResult.getResult().getValue().get()).isEqualTo("2022-05-31T13:47:29.000Z"); + assertThat(successResult.getResult().getValue()).hasValue("2022-05-31T13:47:29.000Z"); } @Test @@ -431,7 +431,7 @@ void canCallFunctionWithMapArgument() { Map resultValue = (Map) successResult.getResult().getValue().get(); - assertThat(resultValue.size()).isEqualTo(1); + assertThat(resultValue).hasSize(1); assertThat(resultValue.get("foobar").getType()).isEqualTo("string"); } @@ -471,7 +471,7 @@ void canCallFunctionWithObjectArgument() { Map resultValue = (Map) successResult.getResult().getValue().get(); - assertThat(resultValue.size()).isEqualTo(1); + assertThat(resultValue).hasSize(1); assertThat(resultValue.get("foobar").getType()).isEqualTo("string"); } diff --git a/java/test/org/openqa/selenium/bidi/script/ScriptCommandsTest.java b/java/test/org/openqa/selenium/bidi/script/ScriptCommandsTest.java index 059ca1bb43814..258a98c59622d 100644 --- a/java/test/org/openqa/selenium/bidi/script/ScriptCommandsTest.java +++ b/java/test/org/openqa/selenium/bidi/script/ScriptCommandsTest.java @@ -17,8 +17,8 @@ package org.openqa.selenium.bidi.script; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.util.ArrayList; import java.util.HashMap; @@ -90,7 +90,7 @@ void canCallFunctionWithArguments() { EvaluateResultSuccess successResult = (EvaluateResultSuccess) result; assertThat(successResult.getResult().getType()).isEqualTo("array"); assertThat(successResult.getResult().getValue().isPresent()).isTrue(); - assertThat(((List) successResult.getResult().getValue().get()).size()).isEqualTo(2); + assertThat(((List) successResult.getResult().getValue().get())).hasSize(2); } @Test @@ -308,7 +308,7 @@ void canCallFunctionThatThrowsException() { assertThat(exception.getExceptionDetails().getText()).contains("SyntaxError:"); assertThat(exception.getExceptionDetails().getLineNumber()).isPositive(); assertThat(exception.getExceptionDetails().getColumnNumber()).isPositive(); - assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames().size()).isEqualTo(0); + assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames()).hasSize(0); } @Test @@ -468,7 +468,7 @@ void canEvaluateScriptThatThrowsException() { assertThat(exception.getExceptionDetails().getException().getType()).isEqualTo("error"); assertThat(exception.getExceptionDetails().getText()).contains("SyntaxError:"); assertThat(exception.getExceptionDetails().getLineNumber()).isGreaterThanOrEqualTo(0); - assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames().size()).isEqualTo(0); + assertThat(exception.getExceptionDetails().getStacktrace().getCallFrames()).hasSize(0); } @Test @@ -686,7 +686,7 @@ void canGetAllRealms() { Script script = new Script(firstWindow, driver); List realms = script.getAllRealms(); - assertThat(realms.size()).isEqualTo(2); + assertThat(realms).hasSize(2); RealmInfo firstWindowRealm = realms.get(0); assertThat(firstWindowRealm.getRealmType()).isEqualTo(RealmType.WINDOW); @@ -711,7 +711,7 @@ void canGetRealmByType() { Script script = new Script(firstWindow, driver); List realms = script.getRealmsByType(RealmType.WINDOW); - assertThat(realms.size()).isEqualTo(2); + assertThat(realms).hasSize(2); RealmInfo firstWindowRealm = realms.get(0); assertThat(firstWindowRealm.getRealmType()).isEqualTo(RealmType.WINDOW); @@ -826,7 +826,7 @@ void canAddPreloadScriptInASandbox() { script.evaluateFunctionInBrowsingContext( driver.getWindowHandle(), "sandbox", "window.bar", true, Optional.empty()); assertThat(result.getResultType()).isEqualTo(EvaluateResult.Type.SUCCESS); - assertThat(((EvaluateResultSuccess) result).getResult().getValue().get()).isEqualTo(2L); + assertThat(((EvaluateResultSuccess) result).getResult().getValue()).hasValue(2L); } @Test @@ -843,7 +843,7 @@ void canRemovePreloadedScript() { script.evaluateFunctionInBrowsingContext( driver.getWindowHandle(), "window.bar", true, Optional.empty()); assertThat(result.getResultType()).isEqualTo(EvaluateResult.Type.SUCCESS); - assertThat(((EvaluateResultSuccess) result).getResult().getValue().get()).isEqualTo(2L); + assertThat(((EvaluateResultSuccess) result).getResult().getValue()).hasValue(2L); script.removePreloadScript(id); diff --git a/java/test/org/openqa/selenium/bidi/script/ScriptEventsTest.java b/java/test/org/openqa/selenium/bidi/script/ScriptEventsTest.java index 8893ff050ab10..354d7a6f510d1 100644 --- a/java/test/org/openqa/selenium/bidi/script/ScriptEventsTest.java +++ b/java/test/org/openqa/selenium/bidi/script/ScriptEventsTest.java @@ -16,8 +16,10 @@ // under the License. package org.openqa.selenium.bidi.script; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.openqa.selenium.testing.drivers.Browser.*; +import static org.assertj.core.api.Assertions.assertThat; +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 java.util.List; import java.util.Optional; @@ -55,11 +57,10 @@ void canListenToChannelMessage() assertThat(message.getChannel()).isEqualTo("channel_name"); assertThat(message.getData().getType()).isEqualTo("string"); assertThat(message.getData().getValue().isPresent()).isTrue(); - assertThat(message.getData().getValue().get()).isEqualTo("foo"); + assertThat(message.getData().getValue()).hasValue("foo"); assertThat(message.getSource().getRealm()).isNotNull(); assertThat(message.getSource().getBrowsingContext().isPresent()).isTrue(); - assertThat(message.getSource().getBrowsingContext().get()) - .isEqualTo(driver.getWindowHandle()); + assertThat(message.getSource().getBrowsingContext()).hasValue(driver.getWindowHandle()); } } diff --git a/java/test/org/openqa/selenium/bidi/storage/StorageCommandsTest.java b/java/test/org/openqa/selenium/bidi/storage/StorageCommandsTest.java index 63f3349c55acb..0aa67cf337d73 100644 --- a/java/test/org/openqa/selenium/bidi/storage/StorageCommandsTest.java +++ b/java/test/org/openqa/selenium/bidi/storage/StorageCommandsTest.java @@ -171,7 +171,7 @@ key, new BytesValue(BytesValue.Type.STRING, value), appServer.getHostName()), GetCookiesResult result1 = storage.getCookies(params1); - assertThat(result1.getCookies().size()).isEqualTo(0); + assertThat(result1.getCookies()).hasSize(0); } @Test @@ -251,7 +251,7 @@ public void canAddAndGetCookie() { assertThat(resultCookie.isSecure()).isEqualTo(false); assertThat(resultCookie.getSameSite()) .isEqualTo(org.openqa.selenium.bidi.network.Cookie.SameSite.LAX); - assertThat(resultCookie.getExpiry().get()).isEqualTo(expiry); + assertThat(resultCookie.getExpiry()).hasValue(expiry); assertThat(key.getSourceOrigin()).isNotNull(); assertThat(key.getUserContext()).isNotNull(); assertThat(key.getUserContext()).isEqualTo("default"); @@ -279,7 +279,7 @@ public void canGetAllCookies() { openAnotherPage(); result = storage.getCookies(params); - assertThat(result.getCookies().size()).isEqualTo(countBefore + 2); + assertThat(result.getCookies()).hasSize(countBefore + 2); assertThat(result.getCookies().get(0).getName().contains(key1)).isTrue(); assertThat(result.getCookies().get(1).getName().contains(key2)).isTrue(); diff --git a/java/test/org/openqa/selenium/chrome/ChromeDriverFunctionalTest.java b/java/test/org/openqa/selenium/chrome/ChromeDriverFunctionalTest.java index ce0d823408d00..1d49cf24b72d9 100644 --- a/java/test/org/openqa/selenium/chrome/ChromeDriverFunctionalTest.java +++ b/java/test/org/openqa/selenium/chrome/ChromeDriverFunctionalTest.java @@ -19,8 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assumptions.assumeThat; import static org.openqa.selenium.testing.drivers.Browser.CHROME; @@ -182,14 +181,10 @@ void canManageNetworkConditions() { conditions.deleteNetworkConditions(); - try { - conditions.getNetworkConditions(); - fail("If Network Conditions were deleted, should not be able to get Network Conditions"); - } catch (WebDriverException e) { - if (!e.getMessage().contains("network conditions must be set before it can be retrieved")) { - throw e; - } - } + assertThatThrownBy(() -> conditions.getNetworkConditions()) + .as("Network Conditions were deleted") + .isInstanceOf(WebDriverException.class) + .hasMessageContaining("network conditions must be set before it can be retrieved"); } @Test @@ -210,12 +205,10 @@ void shouldLaunchSuccessfullyWithArabicDate() { Locale.setDefault(arabicLocale); int port = PortProber.findFreePort(); - ChromeDriverService.Builder builder = new ChromeDriverService.Builder(); - builder.usingPort(port); - builder.build(); - - } catch (Exception e) { - throw e; + try (ChromeDriverService service = + new ChromeDriverService.Builder().usingPort(port).build()) { + assertThat(service.isRunning()).isFalse(); + } } finally { Locale.setDefault(Locale.US); } diff --git a/java/test/org/openqa/selenium/concurrent/LazyTest.java b/java/test/org/openqa/selenium/concurrent/LazyTest.java index 2a4ee77846ec2..4ef92324b5946 100644 --- a/java/test/org/openqa/selenium/concurrent/LazyTest.java +++ b/java/test/org/openqa/selenium/concurrent/LazyTest.java @@ -29,20 +29,20 @@ public class LazyTest { @Test void trivialCase() { - Lazy expression = Lazy.lazy(() -> "constant"); + Lazy expression = Lazy.lazy(() -> "constant"); assertThat(expression.get()).isEqualTo("constant"); assertThat(expression.getIfInitialized()).contains("constant"); } @Test void getIfInitialized_returnsNothing_ifNotInitializedYet() { - Lazy expression = Lazy.lazy(() -> "value#" + counter.incrementAndGet()); + Lazy expression = Lazy.lazy(() -> "value#" + counter.incrementAndGet()); assertThat(expression.getIfInitialized()).isEmpty(); } @Test void lazyEvaluatedExpression() { - Lazy expression = Lazy.lazy(() -> "value#" + counter.incrementAndGet()); + Lazy expression = Lazy.lazy(() -> "value#" + counter.incrementAndGet()); assertThat(expression.get()).isEqualTo("value#1"); assertThat(expression.get()).isEqualTo("value#1"); assertThat(expression.getIfInitialized()).contains("value#1"); @@ -51,8 +51,8 @@ void lazyEvaluatedExpression() { @Test void differentLazyInstances_produce_differentValues() { - Lazy expression1 = Lazy.lazy(() -> "one#" + counter.incrementAndGet()); - Lazy expression2 = Lazy.lazy(() -> "two#" + counter.incrementAndGet()); + Lazy expression1 = Lazy.lazy(() -> "one#" + counter.incrementAndGet()); + Lazy expression2 = Lazy.lazy(() -> "two#" + counter.incrementAndGet()); assertThat(expression1.get()).isEqualTo("one#1"); assertThat(expression1.getIfInitialized()).contains("one#1"); assertThat(expression2.getIfInitialized()).isEmpty(); diff --git a/java/test/org/openqa/selenium/devtools/NetworkInterceptorTest.java b/java/test/org/openqa/selenium/devtools/NetworkInterceptorTest.java index 2999f1666c099..58d8be03698f6 100644 --- a/java/test/org/openqa/selenium/devtools/NetworkInterceptorTest.java +++ b/java/test/org/openqa/selenium/devtools/NetworkInterceptorTest.java @@ -20,8 +20,8 @@ import static com.google.common.net.MediaType.XHTML_UTF_8; import static java.net.HttpURLConnection.HTTP_MOVED_TEMP; import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assumptions.assumeThat; import static org.openqa.selenium.remote.http.Contents.utf8String; import static org.openqa.selenium.testing.Safely.safelyCall; diff --git a/java/test/org/openqa/selenium/docker/client/ListImagesTest.java b/java/test/org/openqa/selenium/docker/client/ListImagesTest.java index 5a117d06b77b0..dce98ed227ff6 100644 --- a/java/test/org/openqa/selenium/docker/client/ListImagesTest.java +++ b/java/test/org/openqa/selenium/docker/client/ListImagesTest.java @@ -74,7 +74,7 @@ void shouldHandleApi144ResponseWithoutVirtualSize() { // Test with API 1.44 - should handle missing VirtualSize gracefully Set images = new ListImages(handler, "1.44").apply(reference); - assertThat(images.size()).isEqualTo(1); + assertThat(images).hasSize(1); Image image = images.iterator().next(); assertThat(image.getId()) @@ -110,7 +110,7 @@ private void testListImages(String apiVersion) { // Test with specified API version Set images = new ListImages(handler, apiVersion).apply(reference); - assertThat(images.size()).isEqualTo(1); + assertThat(images).hasSize(1); Image image = images.iterator().next(); assertThat(image.getId()) diff --git a/java/test/org/openqa/selenium/edge/EdgeDriverFunctionalTest.java b/java/test/org/openqa/selenium/edge/EdgeDriverFunctionalTest.java index eff5739b0a9b5..df8c87af2e490 100644 --- a/java/test/org/openqa/selenium/edge/EdgeDriverFunctionalTest.java +++ b/java/test/org/openqa/selenium/edge/EdgeDriverFunctionalTest.java @@ -19,8 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assumptions.assumeThat; import static org.openqa.selenium.testing.drivers.Browser.EDGE; @@ -176,14 +175,10 @@ void canManageNetworkConditions() { conditions.deleteNetworkConditions(); - try { - conditions.getNetworkConditions(); - fail("If Network Conditions were deleted, should not be able to get Network Conditions"); - } catch (WebDriverException e) { - if (!e.getMessage().contains("network conditions must be set before it can be retrieved")) { - throw e; - } - } + assertThatThrownBy(() -> conditions.getNetworkConditions()) + .as("Network Conditions were deleted") + .isInstanceOf(WebDriverException.class) + .hasMessageContaining("network conditions must be set before it can be retrieved"); } @Test @@ -204,12 +199,9 @@ void shouldLaunchSuccessfullyWithArabicDate() { Locale.setDefault(arabicLocale); int port = PortProber.findFreePort(); - EdgeDriverService.Builder builder = new EdgeDriverService.Builder(); - builder.usingPort(port); - builder.build(); - - } catch (Exception e) { - throw e; + try (EdgeDriverService service = new EdgeDriverService.Builder().usingPort(port).build()) { + assertThat(service.isRunning()).isFalse(); + } } finally { Locale.setDefault(Locale.US); } diff --git a/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java b/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java index ee9a6658cd338..af87a5d01401d 100644 --- a/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java +++ b/java/test/org/openqa/selenium/federatedcredentialmanagement/FederatedCredentialManagementTest.java @@ -127,7 +127,7 @@ void testSelectAccount() { assertThat(dialog.getDialogType()).isEqualTo("AccountChooser"); List accountList = dialog.getAccounts(); - assertThat(accountList.size()).isEqualTo(2); + assertThat(accountList).hasSize(2); dialog.selectAccount(1); } @@ -148,7 +148,7 @@ void testGetAccounts() { assertThat(dialog.getDialogType()).isEqualTo("AccountChooser"); List accountList = dialog.getAccounts(); - assertThat(accountList.size()).isEqualTo(2); + assertThat(accountList).hasSize(2); FederatedCredentialManagementAccount account1 = accountList.get(0); diff --git a/java/test/org/openqa/selenium/firefox/FirefoxDriverTest.java b/java/test/org/openqa/selenium/firefox/FirefoxDriverTest.java index 0c1cee89f88ca..87a37bc0be5d3 100644 --- a/java/test/org/openqa/selenium/firefox/FirefoxDriverTest.java +++ b/java/test/org/openqa/selenium/firefox/FirefoxDriverTest.java @@ -18,8 +18,7 @@ package org.openqa.selenium.firefox; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -111,10 +110,9 @@ void shouldGetMeaningfulExceptionOnBrowserDeath() throws Exception { field.set(driver2, spoof); - driver2.get(pages.formPage); - fail("Should have thrown."); - } catch (UnreachableBrowserException e) { - assertThat(e.getMessage()).contains("Error communicating with the remote browser"); + assertThatThrownBy(() -> driver2.get(pages.formPage)) + .isInstanceOf(UnreachableBrowserException.class) + .hasMessageStartingWith("Error communicating with the remote browser"); } finally { keptExecutor.execute(new Command(sessionId, DriverCommand.QUIT)); } diff --git a/java/test/org/openqa/selenium/firefox/RemoteFirefoxDriverTest.java b/java/test/org/openqa/selenium/firefox/RemoteFirefoxDriverTest.java index e5b716d2cc95a..0b7c484461c11 100644 --- a/java/test/org/openqa/selenium/firefox/RemoteFirefoxDriverTest.java +++ b/java/test/org/openqa/selenium/firefox/RemoteFirefoxDriverTest.java @@ -18,15 +18,13 @@ package org.openqa.selenium.firefox; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatCode; import java.io.File; -import java.net.MalformedURLException; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; -import org.openqa.selenium.WebDriverException; import org.openqa.selenium.build.InProject; import org.openqa.selenium.testing.JupiterTestBase; import org.openqa.selenium.testing.NoDriverAfterTest; @@ -42,11 +40,8 @@ public void shouldAllowRemoteWebDriverBuilderToUseHasExtensions() { String id = ((HasExtensions) driver).installExtension(extension); assertThat(id).isEqualTo("webextensions-selenium-example-v3@example.com"); - try { - ((HasExtensions) driver).uninstallExtension(id); - } catch (WebDriverException ex) { - fail(ex.getMessage()); - } + assertThatCode(() -> ((HasExtensions) driver).uninstallExtension(id)) + .doesNotThrowAnyException(); } @Test @@ -58,7 +53,7 @@ void shouldTakeFullPageScreenshot() { @Test @NoDriverBeforeTest - public void shouldAllowRemoteWebDriverBuilderToUseHasContext() throws MalformedURLException { + public void shouldAllowRemoteWebDriverBuilderToUseHasContext() { FirefoxOptions options = new FirefoxOptions(); String dir = "foo/bar"; options.addPreference("browser.download.dir", dir); diff --git a/java/test/org/openqa/selenium/firefox/TakesFullPageScreenshotTest.java b/java/test/org/openqa/selenium/firefox/TakesFullPageScreenshotTest.java index 978cbc6540f5a..8402c7a2e960b 100644 --- a/java/test/org/openqa/selenium/firefox/TakesFullPageScreenshotTest.java +++ b/java/test/org/openqa/selenium/firefox/TakesFullPageScreenshotTest.java @@ -18,7 +18,6 @@ package org.openqa.selenium.firefox; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; import com.google.common.collect.Sets; @@ -99,7 +98,7 @@ void testGetScreenshotAsBinary() { } @Test - void testShouldCaptureScreenshotOfCurrentViewport() { + void testShouldCaptureScreenshotOfCurrentViewport() throws IOException { driver.get(appServer.whereIs("screen/screen.html")); BufferedImage screenshot = getImage(); @@ -118,7 +117,7 @@ void testShouldCaptureScreenshotOfCurrentViewport() { } @Test - void testShouldCaptureScreenshotOfPageWithLongY() { + void testShouldCaptureScreenshotOfPageWithLongY() throws IOException { driver.get(appServer.whereIs("screen/screen_y_long.html")); BufferedImage screenshot = getImage(); @@ -141,16 +140,11 @@ void testShouldCaptureScreenshotOfPageWithLongY() { * * @return Image object */ - private BufferedImage getImage() { - BufferedImage image = null; - try { - byte[] imageData = screenshooter.getFullPageScreenshotAs(OutputType.BYTES); - assertThat(imageData).isNotNull().isNotEmpty(); - image = ImageIO.read(new ByteArrayInputStream(imageData)); - assertThat(image).isNotNull(); - } catch (IOException e) { - fail("Image screenshot file is invalid: " + e.getMessage()); - } + private BufferedImage getImage() throws IOException { + byte[] imageData = screenshooter.getFullPageScreenshotAs(OutputType.BYTES); + assertThat(imageData).isNotNull().isNotEmpty(); + BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageData)); + assertThat(image).isNotNull(); // saveImageToTmpFile(image); return image; @@ -195,26 +189,22 @@ private Set generateExpectedColors( private Set scanActualColors(BufferedImage image, final int stepX, final int stepY) { Set colors = new TreeSet<>(); - try { - int height = image.getHeight(); - int width = image.getWidth(); - assertThat(width > 0).isTrue(); - assertThat(height > 0).isTrue(); - - Raster raster = image.getRaster(); - for (int i = 0; i < width; i = i + stepX) { - for (int j = 0; j < height; j = j + stepY) { - String hex = - String.format( - "#%02x%02x%02x", - (raster.getSample(i, j, 0)), - (raster.getSample(i, j, 1)), - (raster.getSample(i, j, 2))); - colors.add(hex); - } + int height = image.getHeight(); + int width = image.getWidth(); + assertThat(width > 0).isTrue(); + assertThat(height > 0).isTrue(); + + Raster raster = image.getRaster(); + for (int i = 0; i < width; i = i + stepX) { + for (int j = 0; j < height; j = j + stepY) { + String hex = + String.format( + "#%02x%02x%02x", + (raster.getSample(i, j, 0)), + (raster.getSample(i, j, 1)), + (raster.getSample(i, j, 2))); + colors.add(hex); } - } catch (Exception e) { - fail("Unable to get actual colors from screenshot: " + e.getMessage()); } assertThat(colors).isNotEmpty(); @@ -237,17 +227,7 @@ private void compareColors(Set expectedColors, Set actualColors) cleanActualColors.remove("#000000"); cleanActualColors.remove("#ffffff"); - if (!expectedColors.containsAll(cleanActualColors)) { - fail( - "There are unexpected colors on the screenshot: " - + Sets.difference(cleanActualColors, expectedColors)); - } - - if (!cleanActualColors.containsAll(expectedColors)) { - fail( - "There are expected colors not present on the screenshot: " - + Sets.difference(expectedColors, cleanActualColors)); - } + assertThat(cleanActualColors).containsExactlyInAnyOrderElementsOf(expectedColors); } private boolean onlyBlack(Set colors) { @@ -264,13 +244,9 @@ private boolean onlyWhite(Set colors) { * @param im image */ @SuppressWarnings("unused") - private void saveImageToTmpFile(String methodName, BufferedImage im) { + private void saveImageToTmpFile(String methodName, BufferedImage im) throws IOException { File outputfile = new File(methodName + "_image.png"); - try { - ImageIO.write(im, "png", outputfile); - } catch (IOException e) { - fail("Unable to write image to file: " + e.getMessage()); - } + ImageIO.write(im, "png", outputfile); } } diff --git a/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java b/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java index 5bcbb4c227d6b..166799e5ab9df 100644 --- a/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/DistributorDrainingTest.java @@ -96,7 +96,7 @@ void drainedNodeDoesNotShutDownIfNotEmpty() throws InterruptedException { assertThat(latch.getCount()).isEqualTo(1); - assertThat(local.getStatus().getNodes().size()).isEqualTo(1); + assertThat(local.getStatus().getNodes()).hasSize(1); } @Test @@ -153,7 +153,7 @@ void drainedNodeShutsDownAfterSessionsFinish() throws InterruptedException { local.drain(node.getId()); - assertThat(local.getStatus().getNodes().size()).isEqualTo(1); + assertThat(local.getStatus().getNodes()).hasSize(1); node.stop(firstResponse.right().getSession().getId()); node.stop(secondResponse.right().getSession().getId()); diff --git a/java/test/org/openqa/selenium/grid/distributor/DistributorNodeAvailabilityTest.java b/java/test/org/openqa/selenium/grid/distributor/DistributorNodeAvailabilityTest.java index decce9a583849..54eb595844ea1 100644 --- a/java/test/org/openqa/selenium/grid/distributor/DistributorNodeAvailabilityTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/DistributorNodeAvailabilityTest.java @@ -86,7 +86,7 @@ void registeringTheSameNodeMultipleTimesOnlyCountsTheFirstTime() { DistributorStatus status = local.getStatus(); - assertThat(status.getNodes().size()).isEqualTo(1); + assertThat(status.getNodes()).hasSize(1); } @Test diff --git a/java/test/org/openqa/selenium/grid/distributor/HeartBeatTest.java b/java/test/org/openqa/selenium/grid/distributor/HeartBeatTest.java index d0793ebb75d6a..8222f2ee2e3f4 100644 --- a/java/test/org/openqa/selenium/grid/distributor/HeartBeatTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/HeartBeatTest.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.fail; import java.time.Duration; import java.time.Instant; @@ -36,38 +35,34 @@ public class HeartBeatTest extends DistributorTestBase { @Test - void shouldStartHeartBeatOnNodeStart() { + void shouldStartHeartBeatOnNodeStart() throws InterruptedException { EventBus bus = new GuavaEventBus(); - LocalNode node = + try (LocalNode node = LocalNode.builder(tracer, bus, routableUri, routableUri, registrationSecret) .add( caps, new TestSessionFactory( (id, c) -> new Session(id, nodeUri, stereotype, c, Instant.now()))) .heartbeatPeriod(Duration.ofSeconds(1)) - .build(); + .build()) { - AtomicBoolean heartbeatStarted = new AtomicBoolean(); - CountDownLatch latch = new CountDownLatch(1); + AtomicBoolean heartbeatStarted = new AtomicBoolean(); + CountDownLatch latch = new CountDownLatch(1); - bus.addListener( - NodeHeartBeatEvent.listener( - nodeStatus -> { - if (node.getId().equals(nodeStatus.getNodeId())) { - latch.countDown(); - heartbeatStarted.set(true); - } - })); + bus.addListener( + NodeHeartBeatEvent.listener( + nodeStatus -> { + if (node.getId().equals(nodeStatus.getNodeId())) { + latch.countDown(); + heartbeatStarted.set(true); + } + })); - boolean eventFiredAndListenedTo = false; - try { - eventFiredAndListenedTo = latch.await(30, TimeUnit.SECONDS); - } catch (InterruptedException e) { - fail("Thread Interrupted"); - } + boolean eventFiredAndListenedTo = latch.await(30, TimeUnit.SECONDS); - assertThat(eventFiredAndListenedTo).isTrue(); - assertThat(heartbeatStarted.get()).isTrue(); + assertThat(eventFiredAndListenedTo).isTrue(); + assertThat(heartbeatStarted.get()).isTrue(); + } } } 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 20a138f9b6601..569e85aa19f06 100644 --- a/java/test/org/openqa/selenium/grid/distributor/local/LocalDistributorTest.java +++ b/java/test/org/openqa/selenium/grid/distributor/local/LocalDistributorTest.java @@ -141,7 +141,7 @@ void testAddNodeToDistributor() { // Check the size final Set nodes = status.getNodes(); - assertThat(nodes.size()).isEqualTo(1); + assertThat(nodes).hasSize(1); // Check a couple attributes NodeStatus distributorNode = nodes.iterator().next(); @@ -182,7 +182,7 @@ void testRemoveNodeFromDistributor() { // Check the size DistributorStatus statusBefore = distributor.getStatus(); final Set nodesBefore = statusBefore.getNodes(); - assertThat(nodesBefore.size()).isEqualTo(1); + assertThat(nodesBefore).hasSize(1); // Recheck the status--should be zero distributor.remove(localNode.getId()); @@ -223,7 +223,7 @@ void testAddSameNodeTwice() { // Should only be one node after dupe check final Set nodes = status.getNodes(); - assertThat(nodes.size()).isEqualTo(1); + assertThat(nodes).hasSize(1); } @Test @@ -353,7 +353,7 @@ void testDrainNodeFromDistributor() { // Check the size - there should be one node DistributorStatus statusBefore = distributor.getStatus(); Set nodesBefore = statusBefore.getNodes(); - assertThat(nodesBefore.size()).isEqualTo(1); + assertThat(nodesBefore).hasSize(1); NodeStatus nodeBefore = nodesBefore.iterator().next(); assertThat(nodeBefore.getAvailability()).isNotEqualTo(DRAINING); @@ -482,7 +482,7 @@ void slowStartingNodesShouldNotCauseReservationsToBeSerialized() { try { f.get(); } catch (InterruptedException e) { - fail("Interrupted"); + fail(e.toString(), e); } catch (ExecutionException e) { throw new RuntimeException(e); } 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 babd6692aac39..d752011e820c9 100644 --- a/java/test/org/openqa/selenium/grid/node/config/NodeOptionsTest.java +++ b/java/test/org/openqa/selenium/grid/node/config/NodeOptionsTest.java @@ -21,9 +21,9 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.InstanceOfAssertFactories.LIST; import static org.assertj.core.api.InstanceOfAssertFactories.MAP; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.openqa.selenium.remote.CapabilityType.ENABLE_DOWNLOADS; @@ -304,17 +304,16 @@ void shouldThrowConfigExceptionIfDetectDriversIsFalseAndSpecificDriverIsAdded() "detect-drivers", "false", "driver-implementation", "[chrome]"))); List reported = new ArrayList<>(); - try { - new NodeOptions(config) - .getSessionFactories( - caps -> { - reported.add(caps); - return Collections.singleton(HelperFactory.create(config, caps)); - }); - fail("Should have not executed 'getSessionFactories' successfully"); - } catch (ConfigException e) { - // Fall through - } + assertThatThrownBy( + () -> + new NodeOptions(config) + .getSessionFactories( + caps -> { + reported.add(caps); + return Collections.singleton(HelperFactory.create(config, caps)); + })) + .isInstanceOf(ConfigException.class) + .hasMessage("Specific drivers cannot be added if 'detect-drivers' is set to false"); assertThat(reported).isEmpty(); } @@ -549,19 +548,19 @@ void driversConfigNeedsStereotypeField() { Config config = new TomlConfig(new StringReader(String.join("\n", rawConfig))); List reported = new ArrayList<>(); - try { - new NodeOptions(config) - .getSessionFactories( - caps -> { - reported.add(caps); - return Collections.singleton(HelperFactory.create(config, caps)); - }); - fail( - "Should have not executed 'getSessionFactories' successfully because driver config " - + "needs the stereotype field"); - } catch (ConfigException e) { - // Fall through - } + assertThatThrownBy( + () -> + new NodeOptions(config) + .getSessionFactories( + caps -> { + reported.add(caps); + return Collections.singleton(HelperFactory.create(config, caps)); + })) + .as("driver config needs the stereotype field") + .isInstanceOf(ConfigException.class) + .hasMessage( + "Found config with no 'stereotype' setting! {display-name=Chrome Beta, max-sessions=2," + + " cheese=paipa}"); assertThat(reported).isEmpty(); } diff --git a/java/test/org/openqa/selenium/grid/node/relay/RelayOptionsTest.java b/java/test/org/openqa/selenium/grid/node/relay/RelayOptionsTest.java index e376c13e41fc4..d41ca265309af 100644 --- a/java/test/org/openqa/selenium/grid/node/relay/RelayOptionsTest.java +++ b/java/test/org/openqa/selenium/grid/node/relay/RelayOptionsTest.java @@ -60,7 +60,7 @@ void basicConfigurationIsParsedSuccessfully() { .findFirst() .orElseThrow(() -> new AssertionError("No value returned")); - assertThat(sessionFactories.get(chrome).size()).isEqualTo(2); + assertThat(sessionFactories.get(chrome)).hasSize(2); assertThat(relayOptions.getServiceUri().toString()).isEqualTo("http://localhost:9999"); } diff --git a/java/test/org/openqa/selenium/grid/router/EndToEndTest.java b/java/test/org/openqa/selenium/grid/router/EndToEndTest.java index af228d1620b01..05daa0c19ad03 100644 --- a/java/test/org/openqa/selenium/grid/router/EndToEndTest.java +++ b/java/test/org/openqa/selenium/grid/router/EndToEndTest.java @@ -18,9 +18,9 @@ package org.openqa.selenium.grid.router; 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.junit.jupiter.api.Assertions.fail; 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; @@ -194,27 +194,33 @@ void exerciseDriver(Supplier values) { // The node added only has a single node. Make sure we can start and stop sessions. Capabilities caps = new ImmutableCapabilities("browserName", "cheese", "se:type", "cheddar"); WebDriver driver = new RemoteWebDriver(server.getUrl(), caps); - driver.get("http://www.google.com"); - - // The node is still open. Now create a second session. It will be added to the queue. - // An retry will be attempted and once request times out, it should fail try { - WebDriver disposable = new RemoteWebDriver(server.getUrl(), caps); - disposable.quit(); - fail("Should not have been able to create driver"); - } catch (SessionNotCreatedException expected) { - // Fall through + driver.get("https://www.google.com"); + + // The node is still open. Now try to create a second session. It will be added to the queue. + // A retry will be attempted and once request times out, it should fail. + assertThatThrownBy( + () -> { + WebDriver disposable = new RemoteWebDriver(server.getUrl(), caps); + disposable.quit(); + }) + .as("Should not have been able to create driver") + .isInstanceOf(SessionNotCreatedException.class) + .hasMessageContaining("browserName: cheese, se:type: cheddar"); + } finally { + driver.quit(); } - // Kill the session, and wait until the grid says it's ready - driver.quit(); - + // and wait until the grid says it's ready waitUntilReady(server, Duration.ofSeconds(100)); - // And now we're good to go. - driver = new RemoteWebDriver(server.getUrl(), caps); - driver.get("http://www.google.com"); - driver.quit(); + // And now we can open another browser (because the previous one has been closed). + RemoteWebDriver newWebDriver = new RemoteWebDriver(server.getUrl(), caps); + try { + newWebDriver.get("https://www.google.com"); + } finally { + newWebDriver.quit(); + } } @ParameterizedTest @@ -251,14 +257,15 @@ void shouldAllowPassthroughForW3CMode(Supplier values) { void shouldRejectSessionRequestIfCapsNotSupported(Supplier values) { setFields(values); - try { - Capabilities unsupportedCaps = new ImmutableCapabilities("browserName", "brie"); - WebDriver disposable = new RemoteWebDriver(server.getUrl(), unsupportedCaps); - disposable.quit(); - fail("Should not have been able to create driver"); - } catch (SessionNotCreatedException expected) { - // Fall through - } + assertThatThrownBy( + () -> { + Capabilities unsupportedCaps = new ImmutableCapabilities("browserName", "brie"); + WebDriver disposable = new RemoteWebDriver(server.getUrl(), unsupportedCaps); + disposable.quit(); + }) + .as("Should not have been able to create driver") + .isInstanceOf(SessionNotCreatedException.class) + .hasMessageContaining("Capabilities {browserName: brie}"); } @ParameterizedTest diff --git a/java/test/org/openqa/selenium/grid/router/JmxTest.java b/java/test/org/openqa/selenium/grid/router/JmxTest.java index 0ba51026fb9a7..97e7c7f73056e 100644 --- a/java/test/org/openqa/selenium/grid/router/JmxTest.java +++ b/java/test/org/openqa/selenium/grid/router/JmxTest.java @@ -18,26 +18,14 @@ package org.openqa.selenium.grid.router; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableMap; import java.lang.management.ManagementFactory; import java.net.URI; -import java.net.URISyntaxException; import java.time.Duration; import java.time.Instant; import java.util.logging.Logger; -import javax.management.AttributeList; -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.IntrospectionException; -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanException; -import javax.management.MBeanInfo; -import javax.management.MBeanServer; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; -import javax.management.ReflectionException; +import javax.management.*; import org.junit.jupiter.api.Test; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; @@ -70,187 +58,139 @@ class JmxTest { private final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); @Test - void shouldBeAbleToRegisterBaseServerConfig() { - try { - ObjectName name = new ObjectName("org.seleniumhq.grid:type=Config,name=BaseServerConfig"); - new JMXHelper().unregister(name); + void shouldBeAbleToRegisterBaseServerConfig() throws Exception { + ObjectName name = new ObjectName("org.seleniumhq.grid:type=Config,name=BaseServerConfig"); + new JMXHelper().unregister(name); - BaseServerOptions baseServerOptions = - new BaseServerOptions( - new MapConfig( - ImmutableMap.of("server", ImmutableMap.of("port", PortProber.findFreePort())))); + BaseServerOptions baseServerOptions = + new BaseServerOptions( + new MapConfig( + ImmutableMap.of("server", ImmutableMap.of("port", PortProber.findFreePort())))); - MBeanInfo info = beanServer.getMBeanInfo(name); - assertThat(info).isNotNull(); + MBeanInfo info = beanServer.getMBeanInfo(name); + assertThat(info).isNotNull(); - MBeanAttributeInfo[] attributeInfoArray = info.getAttributes(); - assertThat(attributeInfoArray).hasSize(3); + MBeanAttributeInfo[] attributeInfoArray = info.getAttributes(); + assertThat(attributeInfoArray).hasSize(3); - AttributeList attributeList = getAttributeList(name, attributeInfoArray); - assertThat(attributeList).isNotNull().hasSize(3); - - String uriValue = (String) beanServer.getAttribute(name, "Uri"); - assertThat(uriValue).isEqualTo(baseServerOptions.getExternalUri().toString()); - - } catch (InstanceNotFoundException - | IntrospectionException - | ReflectionException - | MalformedObjectNameException e) { - fail("Could not find the registered MBean"); - } catch (MBeanException e) { - fail("MBeanServer exception"); - } catch (AttributeNotFoundException e) { - fail("Could not find the registered MBean's attribute"); - } + AttributeList attributeList = getAttributeList(name, attributeInfoArray); + assertThat(attributeList).isNotNull().hasSize(3); + + String uriValue = (String) beanServer.getAttribute(name, "Uri"); + assertThat(uriValue).isEqualTo(baseServerOptions.getExternalUri().toString()); } @Test - void shouldBeAbleToRegisterNode() throws URISyntaxException { - try { - URI nodeUri = new URI("https://example.com:1234"); - ObjectName name = new ObjectName("org.seleniumhq.grid:type=Node,name=LocalNode"); - new JMXHelper().unregister(name); - - Tracer tracer = DefaultTestTracer.createTracer(); - EventBus bus = new GuavaEventBus(); + void shouldBeAbleToRegisterNode() throws Exception { + URI nodeUri = new URI("https://example.com:1234"); + ObjectName name = new ObjectName("org.seleniumhq.grid:type=Node,name=LocalNode"); + new JMXHelper().unregister(name); - Secret secret = new Secret("cheese"); + Tracer tracer = DefaultTestTracer.createTracer(); + EventBus bus = new GuavaEventBus(); - LocalNode localNode = - LocalNode.builder(tracer, bus, nodeUri, nodeUri, secret) - .add( - CAPS, - new TestSessionFactory( - (id, caps) -> - new Session( - id, nodeUri, new ImmutableCapabilities(), caps, Instant.now()))) - .build(); + Secret secret = new Secret("cheese"); - assertThat(localNode).isNotNull(); + LocalNode localNode = + LocalNode.builder(tracer, bus, nodeUri, nodeUri, secret) + .add( + CAPS, + new TestSessionFactory( + (id, caps) -> + new Session(id, nodeUri, new ImmutableCapabilities(), caps, Instant.now()))) + .build(); - MBeanInfo info = beanServer.getMBeanInfo(name); - assertThat(info).isNotNull(); + assertThat(localNode).isNotNull(); - MBeanAttributeInfo[] attributeInfo = info.getAttributes(); - assertThat(attributeInfo).hasSize(9); + MBeanInfo info = beanServer.getMBeanInfo(name); + assertThat(info).isNotNull(); - AttributeList attributeList = getAttributeList(name, attributeInfo); - assertThat(attributeList).isNotNull().hasSize(9); + MBeanAttributeInfo[] attributeInfo = info.getAttributes(); + assertThat(attributeInfo).hasSize(9); - Object currentSessions = beanServer.getAttribute(name, "CurrentSessions"); - assertNumberAttribute(currentSessions, 0); + AttributeList attributeList = getAttributeList(name, attributeInfo); + assertThat(attributeList).isNotNull().hasSize(9); - Object maxSessions = beanServer.getAttribute(name, "MaxSessions"); - assertNumberAttribute(maxSessions, 1); + Object currentSessions = beanServer.getAttribute(name, "CurrentSessions"); + assertNumberAttribute(currentSessions, 0); - String status = (String) beanServer.getAttribute(name, "Status"); - assertThat(status).isEqualTo("UP"); + Object maxSessions = beanServer.getAttribute(name, "MaxSessions"); + assertNumberAttribute(maxSessions, 1); - Object totalSlots = beanServer.getAttribute(name, "TotalSlots"); - assertNumberAttribute(totalSlots, 1); + String status = (String) beanServer.getAttribute(name, "Status"); + assertThat(status).isEqualTo("UP"); - Object usedSlots = beanServer.getAttribute(name, "UsedSlots"); - assertNumberAttribute(usedSlots, 0); + Object totalSlots = beanServer.getAttribute(name, "TotalSlots"); + assertNumberAttribute(totalSlots, 1); - Object load = beanServer.getAttribute(name, "Load"); - assertNumberAttribute(load, 0.0f); + Object usedSlots = beanServer.getAttribute(name, "UsedSlots"); + assertNumberAttribute(usedSlots, 0); - String remoteNodeUri = (String) beanServer.getAttribute(name, "RemoteNodeUri"); - assertThat(remoteNodeUri).isEqualTo(nodeUri.toString()); + Object load = beanServer.getAttribute(name, "Load"); + assertNumberAttribute(load, 0.0f); - String gridUri = (String) beanServer.getAttribute(name, "GridUri"); - assertThat(gridUri).isEqualTo(nodeUri.toString()); + String remoteNodeUri = (String) beanServer.getAttribute(name, "RemoteNodeUri"); + assertThat(remoteNodeUri).isEqualTo(nodeUri.toString()); - } catch (InstanceNotFoundException - | IntrospectionException - | ReflectionException - | MalformedObjectNameException e) { - fail("Could not find the registered MBean"); - } catch (MBeanException e) { - fail("MBeanServer exception"); - } catch (AttributeNotFoundException e) { - fail("Could not find the registered MBean's attribute"); - } + String gridUri = (String) beanServer.getAttribute(name, "GridUri"); + assertThat(gridUri).isEqualTo(nodeUri.toString()); } @Test - void shouldBeAbleToRegisterSessionQueueServerConfig() { - try { - ObjectName name = - new ObjectName("org.seleniumhq.grid:type=Config,name=NewSessionQueueConfig"); + void shouldBeAbleToRegisterSessionQueueServerConfig() throws Exception { + ObjectName name = new ObjectName("org.seleniumhq.grid:type=Config,name=NewSessionQueueConfig"); - new JMXHelper().unregister(name); + new JMXHelper().unregister(name); - NewSessionQueueOptions newSessionQueueOptions = - new NewSessionQueueOptions(new MapConfig(ImmutableMap.of())); - MBeanInfo info = beanServer.getMBeanInfo(name); - assertThat(info).isNotNull(); + NewSessionQueueOptions newSessionQueueOptions = + new NewSessionQueueOptions(new MapConfig(ImmutableMap.of())); + MBeanInfo info = beanServer.getMBeanInfo(name); + assertThat(info).isNotNull(); - MBeanAttributeInfo[] attributeInfoArray = info.getAttributes(); - assertThat(attributeInfoArray).hasSize(2); + MBeanAttributeInfo[] attributeInfoArray = info.getAttributes(); + assertThat(attributeInfoArray).hasSize(2); - AttributeList attributeList = getAttributeList(name, attributeInfoArray); - assertThat(attributeList).isNotNull().hasSize(2); - - Object requestTimeout = beanServer.getAttribute(name, "RequestTimeoutSeconds"); - assertNumberAttribute(requestTimeout, newSessionQueueOptions.getRequestTimeoutSeconds()); - - Object retryInterval = beanServer.getAttribute(name, "RetryIntervalMilliseconds"); - assertNumberAttribute(retryInterval, newSessionQueueOptions.getRetryIntervalMilliseconds()); - } catch (InstanceNotFoundException - | IntrospectionException - | ReflectionException - | MalformedObjectNameException e) { - fail("Could not find the registered MBean"); - } catch (MBeanException e) { - fail("MBeanServer exception"); - } catch (AttributeNotFoundException e) { - fail("Could not find the registered MBean's attribute"); - } + AttributeList attributeList = getAttributeList(name, attributeInfoArray); + assertThat(attributeList).isNotNull().hasSize(2); + + Object requestTimeout = beanServer.getAttribute(name, "RequestTimeoutSeconds"); + assertNumberAttribute(requestTimeout, newSessionQueueOptions.getRequestTimeoutSeconds()); + + Object retryInterval = beanServer.getAttribute(name, "RetryIntervalMilliseconds"); + assertNumberAttribute(retryInterval, newSessionQueueOptions.getRetryIntervalMilliseconds()); } @Test - void shouldBeAbleToRegisterSessionQueue() { - try { - ObjectName name = - new ObjectName("org.seleniumhq.grid:type=SessionQueue,name=LocalSessionQueue"); - - new JMXHelper().unregister(name); - - Tracer tracer = DefaultTestTracer.createTracer(); - - NewSessionQueue sessionQueue = - new LocalNewSessionQueue( - tracer, - new DefaultSlotMatcher(), - Duration.ofSeconds(2), - Duration.ofSeconds(2), - Duration.ofSeconds(1), - new Secret(""), - 5); - - assertThat(sessionQueue).isNotNull(); - MBeanInfo info = beanServer.getMBeanInfo(name); - assertThat(info).isNotNull(); + void shouldBeAbleToRegisterSessionQueue() throws Exception { + ObjectName name = + new ObjectName("org.seleniumhq.grid:type=SessionQueue,name=LocalSessionQueue"); - MBeanAttributeInfo[] attributeInfoArray = info.getAttributes(); - assertThat(attributeInfoArray).hasSize(1); + new JMXHelper().unregister(name); - AttributeList attributeList = getAttributeList(name, attributeInfoArray); - assertThat(attributeList).isNotNull().hasSize(1); - - Object size = beanServer.getAttribute(name, "NewSessionQueueSize"); - assertNumberAttribute(size, 0); - } catch (InstanceNotFoundException - | IntrospectionException - | ReflectionException - | MalformedObjectNameException e) { - fail("Could not find the registered MBean"); - } catch (MBeanException e) { - fail("MBeanServer exception"); - } catch (AttributeNotFoundException e) { - fail("Could not find the registered MBean's attribute"); - } + Tracer tracer = DefaultTestTracer.createTracer(); + + NewSessionQueue sessionQueue = + new LocalNewSessionQueue( + tracer, + new DefaultSlotMatcher(), + Duration.ofSeconds(2), + Duration.ofSeconds(2), + Duration.ofSeconds(1), + new Secret(""), + 5); + + assertThat(sessionQueue).isNotNull(); + MBeanInfo info = beanServer.getMBeanInfo(name); + assertThat(info).isNotNull(); + + MBeanAttributeInfo[] attributeInfoArray = info.getAttributes(); + assertThat(attributeInfoArray).hasSize(1); + + AttributeList attributeList = getAttributeList(name, attributeInfoArray); + assertThat(attributeList).isNotNull().hasSize(1); + + Object size = beanServer.getAttribute(name, "NewSessionQueueSize"); + assertNumberAttribute(size, 0); } @Test diff --git a/java/test/org/openqa/selenium/grid/router/ProxyWebsocketTest.java b/java/test/org/openqa/selenium/grid/router/ProxyWebsocketTest.java index 54ffd00c75873..7860eb16d97cb 100644 --- a/java/test/org/openqa/selenium/grid/router/ProxyWebsocketTest.java +++ b/java/test/org/openqa/selenium/grid/router/ProxyWebsocketTest.java @@ -141,7 +141,7 @@ void shouldForwardTextMessageToServer(Supplier values) socket.sendText("Cheese!"); assertThat(latch.await(5, SECONDS)).isTrue(); - assertThat(text.get()).isEqualTo("Cheese!"); + assertThat(text).hasValue("Cheese!"); } } @@ -184,7 +184,7 @@ public void onText(CharSequence data) { socket.sendText("Cheese!"); assertThat(latch.await(5, SECONDS)).isTrue(); - assertThat(text.get()).isEqualTo("Asiago"); + assertThat(text).hasValue("Asiago"); } } @@ -272,7 +272,7 @@ public void onText(CharSequence data) { socket.sendText("Cheese!"); assertThat(latch.await(5, SECONDS)).isTrue(); - assertThat(text.get()).isEqualTo("Cheddar"); + assertThat(text).hasValue("Cheddar"); } secureProxyServer.stop(); diff --git a/java/test/org/openqa/selenium/grid/router/RemoteWebDriverBiDiTest.java b/java/test/org/openqa/selenium/grid/router/RemoteWebDriverBiDiTest.java index 169cc919b5fb0..3104b66e4231a 100644 --- a/java/test/org/openqa/selenium/grid/router/RemoteWebDriverBiDiTest.java +++ b/java/test/org/openqa/selenium/grid/router/RemoteWebDriverBiDiTest.java @@ -17,8 +17,9 @@ package org.openqa.selenium.grid.router; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.openqa.selenium.testing.drivers.Browser.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.openqa.selenium.testing.drivers.Browser.IE; +import static org.openqa.selenium.testing.drivers.Browser.SAFARI; import java.io.StringReader; import java.util.Objects; @@ -111,7 +112,7 @@ void canListenToLogs() throws ExecutionException, InterruptedException, TimeoutE assertThat(source.getBrowsingContext().isPresent()).isTrue(); assertThat(source.getRealm()).isNotNull(); assertThat(logEntry.getText()).isEqualTo("Hello, world!"); - assertThat(logEntry.getArgs().size()).isEqualTo(1); + assertThat(logEntry.getArgs()).hasSize(1); assertThat(logEntry.getType()).isEqualTo("console"); assertThat(logEntry.getLevel()).isEqualTo(LogLevel.INFO); assertThat(logEntry.getMethod()).isEqualTo("log"); diff --git a/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java b/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java index de62101f5259a..df5aa945908a8 100644 --- a/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java +++ b/java/test/org/openqa/selenium/grid/router/RemoteWebDriverDownloadTest.java @@ -41,12 +41,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.openqa.selenium.By; -import org.openqa.selenium.Capabilities; -import org.openqa.selenium.HasDownloads; -import org.openqa.selenium.PersistentCapabilities; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriverException; +import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.environment.webserver.NettyAppServer; import org.openqa.selenium.grid.config.TomlConfig; diff --git a/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java b/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java index e5692dc9ec4dd..03f249dba1758 100644 --- a/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java +++ b/java/test/org/openqa/selenium/grid/router/SessionCleanUpTest.java @@ -19,7 +19,6 @@ import static java.net.HttpURLConnection.HTTP_OK; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import static org.openqa.selenium.grid.data.Availability.DOWN; import static org.openqa.selenium.grid.data.Availability.UP; import static org.openqa.selenium.remote.Dialect.W3C; @@ -240,11 +239,7 @@ void shouldRemoveSessionAfterNodeIsShutDownGracefully() { waitTillNodesAreRemoved(distributor); - try { - waitTillSessionIsRemoved(sessions, id); - } catch (Exception e) { - fail("Session not removed"); - } + waitTillSessionIsRemoved(sessions, id); } } @@ -321,11 +316,7 @@ void shouldRemoveSessionAfterNodeIsDown() throws URISyntaxException { waitTillNodesAreRemoved(distributor); - try { - waitTillSessionIsRemoved(sessions, id); - } catch (Exception e) { - fail("Session not removed"); - } + waitTillSessionIsRemoved(sessions, id); Either sessionResponse = distributor.newSession( diff --git a/java/test/org/openqa/selenium/grid/router/SessionQueueGridTest.java b/java/test/org/openqa/selenium/grid/router/SessionQueueGridTest.java index cf7d1bc67b754..cfd4db0e6c01a 100644 --- a/java/test/org/openqa/selenium/grid/router/SessionQueueGridTest.java +++ b/java/test/org/openqa/selenium/grid/router/SessionQueueGridTest.java @@ -21,7 +21,6 @@ import static java.net.HttpURLConnection.HTTP_OK; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; import static org.openqa.selenium.remote.http.Contents.asJson; import static org.openqa.selenium.remote.http.HttpMethod.DELETE; import static org.openqa.selenium.remote.http.HttpMethod.POST; @@ -34,13 +33,7 @@ import java.time.Instant; import java.util.Arrays; import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeoutException; +import java.util.concurrent.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -157,7 +150,7 @@ public void setup() throws URISyntaxException, MalformedURLException { } @Test - void shouldBeAbleToCreateMultipleSessions() { + void shouldBeAbleToCreateMultipleSessions() throws Exception { ImmutableMap caps = ImmutableMap.of("browserName", "cheese"); ExecutorService fixedThreadPoolService = Executors.newFixedThreadPool(2); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @@ -171,12 +164,6 @@ void shouldBeAbleToCreateMultipleSessions() { HttpResponse httpResponse = future.get(10, SECONDS); assertThat(httpResponse.getStatus()).isEqualTo(HTTP_OK); } - } catch (InterruptedException e) { - fail("Unable to create session. Thread Interrupted"); - } catch (ExecutionException e) { - fail("Unable to create session due to execution exception."); - } catch (TimeoutException e) { - fail("Unable to create session. Timeout occurred."); } finally { fixedThreadPoolService.shutdownNow(); scheduler.shutdownNow(); @@ -191,7 +178,7 @@ void shouldBeAbleToRejectRequest() { } @Test - void shouldBeAbleToClearQueue() { + void shouldBeAbleToClearQueue() throws Exception { ImmutableMap caps = ImmutableMap.of("browserName", "cheese"); ExecutorService fixedThreadPoolService = Executors.newFixedThreadPool(1); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @@ -226,12 +213,6 @@ void shouldBeAbleToClearQueue() { HttpResponse thirdSessionResponse = thirdSessionFuture.get(); assertThat(thirdSessionResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); - } catch (InterruptedException e) { - fail("Unable to create session. Thread Interrupted"); - } catch (ExecutionException e) { - fail("Unable to create session due to execution exception."); - } catch (TimeoutException e) { - fail("Unable to create session. Timeout occurred."); } finally { fixedThreadPoolService.shutdownNow(); scheduler.shutdownNow(); diff --git a/java/test/org/openqa/selenium/grid/router/SessionQueueGridWithTimeoutTest.java b/java/test/org/openqa/selenium/grid/router/SessionQueueGridWithTimeoutTest.java index 7e3f0bd93e7e9..87862f55aec49 100644 --- a/java/test/org/openqa/selenium/grid/router/SessionQueueGridWithTimeoutTest.java +++ b/java/test/org/openqa/selenium/grid/router/SessionQueueGridWithTimeoutTest.java @@ -20,7 +20,6 @@ import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; import static org.openqa.selenium.remote.http.Contents.asJson; import static org.openqa.selenium.remote.http.HttpMethod.POST; @@ -32,12 +31,10 @@ import java.time.Instant; import java.util.List; import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -156,7 +153,7 @@ public void setup() throws URISyntaxException, MalformedURLException { } @Test - void shouldBeAbleToDeleteTimedoutSessions() { + void shouldBeAbleToDeleteTimedOutSessions() throws Exception { ImmutableMap caps = ImmutableMap.of("browserName", "cheese"); ExecutorService fixedThreadPoolService = Executors.newFixedThreadPool(1); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @@ -177,13 +174,6 @@ void shouldBeAbleToDeleteTimedoutSessions() { .withTimeout(Duration.ofSeconds(7)) .until(node -> node.getUsedSlots() == 0); } - - } catch (InterruptedException e) { - fail("Unable to create session. Thread Interrupted"); - } catch (ExecutionException e) { - fail("Unable to create session due to execution exception."); - } catch (TimeoutException e) { - fail("Unable to create session. Timeout occurred."); } finally { fixedThreadPoolService.shutdownNow(); scheduler.shutdownNow(); 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 4ba3f678164c3..e0768cba9b78b 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,7 @@ package org.openqa.selenium.grid.sessionmap.jdbc; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; @@ -129,17 +128,15 @@ void shouldBeAbleToRemoveSessions() throws URISyntaxException { new ImmutableCapabilities("key", "value"), Instant.now()); sessions.add(expected); + SessionId sessionId = expected.getId(); SessionMap reader = getSessionMap(); - reader.remove(expected.getId()); + reader.remove(sessionId); - try { - reader.get(expected.getId()); - fail("Oh noes!"); - } catch (NoSuchSessionException ignored) { - // This is expected - } + assertThatThrownBy(() -> reader.get(sessionId)) + .isInstanceOf(NoSuchSessionException.class) + .hasMessageStartingWith("Unable to find session with id: " + sessionId); } private JdbcBackedSessionMap getSessionMap() { 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 ce8ebfe4254cc..c1f283108769c 100644 --- a/java/test/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMapTest.java +++ b/java/test/org/openqa/selenium/grid/sessionmap/redis/RedisBackedSessionMapTest.java @@ -17,8 +17,7 @@ package org.openqa.selenium.grid.sessionmap.redis; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.openqa.selenium.testing.Safely.safelyCall; @@ -120,11 +119,7 @@ void shouldBeAbleToRemoveSessions() throws URISyntaxException { sessions.remove(expected.getId()); - try { - sessions.get(expected.getId()); - fail("Oh noes!"); - } catch (NoSuchSessionException ignored) { - // This is expected - } + assertThatThrownBy(() -> sessions.get(expected.getId())) + .isInstanceOf(NoSuchSessionException.class); } } diff --git a/java/test/org/openqa/selenium/grid/sessionqueue/local/LocalNewSessionQueueTest.java b/java/test/org/openqa/selenium/grid/sessionqueue/local/LocalNewSessionQueueTest.java index 18a1625ecc385..fce2cea5d1bf7 100644 --- a/java/test/org/openqa/selenium/grid/sessionqueue/local/LocalNewSessionQueueTest.java +++ b/java/test/org/openqa/selenium/grid/sessionqueue/local/LocalNewSessionQueueTest.java @@ -20,14 +20,10 @@ import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; import static java.net.HttpURLConnection.HTTP_OK; import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.UUID.randomUUID; 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.assertj.core.api.Assertions.fail; -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.assertTrue; import static org.openqa.selenium.remote.Dialect.W3C; import static org.openqa.selenium.testing.Safely.safelyCall; @@ -37,20 +33,8 @@ import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeoutException; +import java.util.*; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @@ -64,12 +48,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.RequestId; -import org.openqa.selenium.grid.data.Session; -import org.openqa.selenium.grid.data.SessionRequest; -import org.openqa.selenium.grid.data.SessionRequestCapability; +import org.openqa.selenium.grid.data.*; import org.openqa.selenium.grid.security.Secret; import org.openqa.selenium.grid.sessionqueue.NewSessionQueue; import org.openqa.selenium.grid.sessionqueue.remote.RemoteNewSessionQueue; @@ -78,7 +57,6 @@ import org.openqa.selenium.internal.Either; import org.openqa.selenium.json.Json; 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.HttpResponse; import org.openqa.selenium.remote.tracing.DefaultTestTracer; @@ -103,7 +81,7 @@ public void setup(Supplier supplier) { this.sessionRequest = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(CAPS), @@ -213,6 +191,7 @@ void testCompleteWithCreatedSession(Supplier supplier) throws Interrup assertThat(latch.await(1000, MILLISECONDS)).isTrue(); assertThat(isCompleted.get()).isTrue(); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_OK); } @ParameterizedTest @@ -261,6 +240,7 @@ void testCompleteWithSessionInTimeout(Supplier supplier) throws Interr HttpResponse httpResponse = queue.addToQueue(sessionRequest); assertThat(latch.await(3000, MILLISECONDS)).isTrue(); assertThat(isCompleted.get()).isFalse(); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); } @ParameterizedTest @@ -302,7 +282,7 @@ void shouldBeAbleToAddToQueueAndGetValidResponse(Supplier supplier) { HttpResponse httpResponse = queue.addToQueue(sessionRequest); assertThat(isPresent.get()).isTrue(); - assertEquals(HTTP_OK, httpResponse.getStatus()); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_OK); } @ParameterizedTest @@ -313,7 +293,7 @@ void shouldBeAbleToAddToQueueWithTimeoutDoNotCreateSessionAfterTimeout( SessionRequest sessionRequestWithTimeout = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(CAPS), @@ -356,7 +336,7 @@ void shouldBeAbleToAddToQueueWithTimeoutDoNotCreateSessionAfterTimeout( assertThat(LocalDateTime.now().minusSeconds(10).isBefore(start)).isTrue(); assertThat(isPresent.get()).isTrue(); - assertEquals(HTTP_INTERNAL_ERROR, httpResponse.getStatus()); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); } @ParameterizedTest @@ -366,7 +346,7 @@ void shouldBeAbleToAddToQueueWithTimeoutAndTimeoutResponse(Supplier su SessionRequest sessionRequestWithTimeout = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(CAPS), @@ -414,7 +394,7 @@ void shouldBeAbleToAddToQueueWithTimeoutAndTimeoutResponse(Supplier su HttpResponse httpResponse = queue.addToQueue(sessionRequestWithTimeout); assertThat(isPresent.get()).isTrue(); - assertEquals(HTTP_INTERNAL_ERROR, httpResponse.getStatus()); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); } @ParameterizedTest @@ -433,7 +413,7 @@ void shouldBeAbleToAddToQueueAndGetErrorResponse(Supplier supplier) { HttpResponse httpResponse = queue.addToQueue(sessionRequest); - assertEquals(HTTP_INTERNAL_ERROR, httpResponse.getStatus()); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); } @ParameterizedTest @@ -441,9 +421,9 @@ void shouldBeAbleToAddToQueueAndGetErrorResponse(Supplier supplier) { void shouldBeAbleToRemoveFromQueue(Supplier supplier) { setup(supplier); - Optional httpRequest = queue.remove(new RequestId(UUID.randomUUID())); + Optional httpRequest = queue.remove(new RequestId(randomUUID())); - assertFalse(httpRequest.isPresent()); + assertThat(httpRequest).isEmpty(); } @ParameterizedTest @@ -451,13 +431,13 @@ void shouldBeAbleToRemoveFromQueue(Supplier supplier) { void shouldBeClearQueue(Supplier supplier) { setup(supplier); - RequestId requestId = new RequestId(UUID.randomUUID()); + RequestId requestId = new RequestId(randomUUID()); localQueue.injectIntoQueue(sessionRequest); int count = queue.clearQueue(); - assertEquals(1, count); - assertFalse(queue.remove(requestId).isPresent()); + assertThat(count).isEqualTo(1); + assertThat(queue.remove(requestId)).isEmpty(); } @ParameterizedTest @@ -472,9 +452,7 @@ void shouldBeAbleToGetQueueContents(Supplier supplier) { .map(SessionRequestCapability::getDesiredCapabilities) .collect(Collectors.toList()); - assertThat(response).hasSize(1); - - assertEquals(Set.of(CAPS), response.get(0)); + assertThat(response).containsExactly(Set.of(CAPS)); } @ParameterizedTest @@ -490,8 +468,8 @@ void queueCountShouldBeReturnedWhenQueueIsCleared(Supplier supplier) { int count = queue.clearQueue(); - assertEquals(1, count); - assertFalse(queue.remove(requestId).isPresent()); + assertThat(count).isEqualTo(1); + assertThat(queue.remove(requestId)).isEmpty(); } @ParameterizedTest @@ -500,9 +478,9 @@ void removingARequestIdThatDoesNotExistInTheQueueShouldNotBeAnError(Supplier httpRequest = queue.remove(new RequestId(UUID.randomUUID())); + Optional httpRequest = queue.remove(new RequestId(randomUUID())); - assertFalse(httpRequest.isPresent()); + assertThat(httpRequest).isEmpty(); } @ParameterizedTest @@ -516,7 +494,7 @@ void shouldBeAbleToAddAgainToQueue(Supplier supplier) { assertThat(removed).isPresent(); boolean added = queue.retryAddToQueue(sessionRequest); - assertTrue(added); + assertThat(added).isTrue(); } @ParameterizedTest @@ -580,13 +558,14 @@ void shouldBeAbleToRetryRequest(Supplier supplier) { assertThat(isPresent.get()).isTrue(); assertThat(retrySuccess.get()).isTrue(); - assertEquals(HTTP_OK, httpResponse.getStatus()); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_OK); } @ParameterizedTest @MethodSource("data") @Timeout(5) - void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime(Supplier supplier) { + void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime(Supplier supplier) + throws ExecutionException, InterruptedException, TimeoutException { setup(supplier); AtomicBoolean processQueue = new AtomicBoolean(true); @@ -602,7 +581,7 @@ void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime(Supplier ImmutableCapabilities capabilities = new ImmutableCapabilities("browserName", "chrome"); try { - SessionId sessionId = new SessionId(UUID.randomUUID()); + SessionId sessionId = new SessionId(randomUUID()); Session session = new Session( sessionId, @@ -631,41 +610,37 @@ void shouldBeAbleToHandleMultipleSessionRequestsAtTheSameTime(Supplier .start(); ExecutorService executor = Executors.newFixedThreadPool(2); - - Callable callable = - () -> { - SessionRequest sessionRequest = - new SessionRequest( - new RequestId(UUID.randomUUID()), - Instant.now(), - Set.of(W3C), - Set.of(CAPS), - Map.of(), - Map.of()); - - return queue.addToQueue(sessionRequest); - }; - - Future firstRequest = executor.submit(callable); - Future secondRequest = executor.submit(callable); - try { + Callable callable = + () -> { + SessionRequest sessionRequest = + new SessionRequest( + new RequestId(randomUUID()), + Instant.now(), + Set.of(W3C), + Set.of(CAPS), + Map.of(), + Map.of()); + + return queue.addToQueue(sessionRequest); + }; + + Future firstRequest = executor.submit(callable); + Future secondRequest = executor.submit(callable); + HttpResponse firstResponse = firstRequest.get(30, SECONDS); HttpResponse secondResponse = secondRequest.get(30, SECONDS); - String firstResponseContents = Contents.string(firstResponse); - String secondResponseContents = Contents.string(secondResponse); - - assertEquals(HTTP_OK, firstResponse.getStatus()); - assertEquals(HTTP_OK, secondResponse.getStatus()); + String firstResponseContents = firstResponse.contentAsString(); + String secondResponseContents = secondResponse.contentAsString(); - assertNotEquals(firstResponseContents, secondResponseContents); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - fail("Could not create session"); + assertThat(firstResponse.getStatus()).isEqualTo(HTTP_OK); + assertThat(secondResponse.getStatus()).isEqualTo(HTTP_OK); + assertThat(secondResponseContents).isNotEqualTo(firstResponseContents); + } finally { + executor.shutdown(); + processQueue.set(false); } - - executor.shutdown(); - processQueue.set(false); } @ParameterizedTest @@ -676,60 +651,53 @@ void shouldBeAbleToTimeoutARequestOnRetry(Supplier supplier) { final SessionRequest request = new SessionRequest( - new RequestId(UUID.randomUUID()), - LONG_AGO, - Set.of(W3C), - Set.of(CAPS), - Map.of(), - Map.of()); + new RequestId(randomUUID()), LONG_AGO, Set.of(W3C), Set.of(CAPS), Map.of(), Map.of()); HttpResponse httpResponse = queue.addToQueue(request); - assertEquals(HTTP_INTERNAL_ERROR, httpResponse.getStatus()); + assertThat(httpResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); } @ParameterizedTest @MethodSource("data") @Timeout(5) - void shouldBeAbleToClearQueueAndRejectMultipleRequests(Supplier supplier) { + void shouldBeAbleToClearQueueAndRejectMultipleRequests(Supplier supplier) + throws ExecutionException, InterruptedException, TimeoutException { setup(supplier); ExecutorService executor = Executors.newFixedThreadPool(2); - Callable callable = - () -> { - SessionRequest sessionRequest = - new SessionRequest( - new RequestId(UUID.randomUUID()), - Instant.now(), - Set.of(W3C), - Set.of(CAPS), - Map.of(), - Map.of()); - return queue.addToQueue(sessionRequest); - }; - - Future firstRequest = executor.submit(callable); - Future secondRequest = executor.submit(callable); - - int count = 0; - - while (count < 2) { - count += queue.clearQueue(); - } - try { + Callable callable = + () -> { + SessionRequest sessionRequest = + new SessionRequest( + new RequestId(randomUUID()), + Instant.now(), + Set.of(W3C), + Set.of(CAPS), + Map.of(), + Map.of()); + return queue.addToQueue(sessionRequest); + }; + + Future firstRequest = executor.submit(callable); + Future secondRequest = executor.submit(callable); + + int count = 0; + + while (count < 2) { + count += queue.clearQueue(); + } + HttpResponse firstResponse = firstRequest.get(30, SECONDS); HttpResponse secondResponse = secondRequest.get(30, SECONDS); - assertEquals(HTTP_INTERNAL_ERROR, firstResponse.getStatus()); - assertEquals(HTTP_INTERNAL_ERROR, secondResponse.getStatus()); - - } catch (InterruptedException | ExecutionException | TimeoutException e) { - fail("Could not create session"); + assertThat(firstResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); + assertThat(secondResponse.getStatus()).isEqualTo(HTTP_INTERNAL_ERROR); + } finally { + executor.shutdownNow(); } - - executor.shutdownNow(); } @ParameterizedTest @@ -740,7 +708,7 @@ void shouldBeAbleToReturnTheNextAvailableEntryThatMatchesAStereotype( SessionRequest expected = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "cheese", "se:kind", "smoked")), @@ -750,7 +718,7 @@ void shouldBeAbleToReturnTheNextAvailableEntryThatMatchesAStereotype( localQueue.injectIntoQueue( new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "peas", "se:kind", "mushy")), @@ -762,6 +730,7 @@ void shouldBeAbleToReturnTheNextAvailableEntryThatMatchesAStereotype( List returned = queue.getNextAvailable(stereotypes); + assertThat(returned).hasSize(1); assertThat(returned.get(0)).isEqualTo(expected); } @@ -773,7 +742,7 @@ void shouldBeAbleToReturnTheNextAvailableBatchThatMatchesStereotypes( SessionRequest firstSessionRequest = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "cheese", "se:kind", "smoked")), @@ -782,7 +751,7 @@ void shouldBeAbleToReturnTheNextAvailableBatchThatMatchesStereotypes( SessionRequest secondSessionRequest = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "peas", "se:kind", "smoked")), @@ -791,7 +760,7 @@ void shouldBeAbleToReturnTheNextAvailableBatchThatMatchesStereotypes( SessionRequest thirdSessionRequest = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "peas", "se:kind", "smoked")), @@ -808,10 +777,10 @@ void shouldBeAbleToReturnTheNextAvailableBatchThatMatchesStereotypes( List returned = queue.getNextAvailable(stereotypes); - assertThat(returned.size()).isEqualTo(3); - assertTrue(returned.contains(firstSessionRequest)); - assertTrue(returned.contains(secondSessionRequest)); - assertTrue(returned.contains(thirdSessionRequest)); + assertThat(returned).hasSize(3); + assertThat(returned).contains(firstSessionRequest); + assertThat(returned.contains(secondSessionRequest)).isTrue(); + assertThat(returned.contains(thirdSessionRequest)).isTrue(); } @ParameterizedTest @@ -825,7 +794,7 @@ void shouldNotReturnANextAvailableEntryThatDoesNotMatchTheStereotypes( // that doesn't match should be first in the queue. localQueue.injectIntoQueue( new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "peas", "se:kind", "mushy")), @@ -834,7 +803,7 @@ void shouldNotReturnANextAvailableEntryThatDoesNotMatchTheStereotypes( SessionRequest expected = new SessionRequest( - new RequestId(UUID.randomUUID()), + new RequestId(randomUUID()), Instant.now(), Set.of(W3C), Set.of(new ImmutableCapabilities("browserName", "cheese", "se:kind", "smoked")), @@ -847,6 +816,7 @@ void shouldNotReturnANextAvailableEntryThatDoesNotMatchTheStereotypes( List returned = queue.getNextAvailable(stereotypes); + assertThat(returned).hasSize(1); assertThat(returned.get(0)).isEqualTo(expected); } diff --git a/java/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java b/java/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java index 70ade3fbe332f..052b34b95b0a3 100644 --- a/java/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java +++ b/java/test/org/openqa/selenium/ie/InternetExplorerDriverTest.java @@ -19,8 +19,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.ie.InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING; +import static org.openqa.selenium.ie.InternetExplorerDriverService.IE_DRIVER_NAME; import java.awt.*; import java.time.Duration; @@ -153,12 +154,10 @@ void shouldLaunchSuccessfullyWithArabicDate() { Locale.setDefault(arabicLocale); int port = PortProber.findFreePort(); - InternetExplorerDriverService.Builder builder = new InternetExplorerDriverService.Builder(); - builder.usingPort(port); - builder.build(); - - } catch (Exception e) { - throw e; + try (InternetExplorerDriverService service = + new InternetExplorerDriverService.Builder().usingPort(port).build()) { + assertThat(service.getDriverName()).isEqualTo(IE_DRIVER_NAME); + } } finally { Locale.setDefault(Locale.US); } diff --git a/java/test/org/openqa/selenium/interactions/DragAndDropTest.java b/java/test/org/openqa/selenium/interactions/DragAndDropTest.java index 16579a729e0db..f866ac6a79618 100644 --- a/java/test/org/openqa/selenium/interactions/DragAndDropTest.java +++ b/java/test/org/openqa/selenium/interactions/DragAndDropTest.java @@ -18,7 +18,7 @@ package org.openqa.selenium.interactions; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.openqa.selenium.WaitingConditions.elementLocationToBe; import static org.openqa.selenium.testing.drivers.Browser.CHROME; import static org.openqa.selenium.testing.drivers.Browser.FIREFOX; @@ -131,17 +131,18 @@ void testDragTooFar() { driver.get(pages.dragAndDropPage); Actions actions = new Actions(driver); - try { - WebElement img = driver.findElement(By.id("test1")); + assertThatThrownBy( + () -> { + WebElement img = driver.findElement(By.id("test1")); - // Attempt to drag the image outside of the bounds of the page. + // Attempt to drag the image outside the bounds of the page. + actions.dragAndDropBy(img, Integer.MAX_VALUE, Integer.MAX_VALUE).perform(); + }) + .as("These coordinates are outside the page - expected to fail.") + .isInstanceOf(MoveTargetOutOfBoundsException.class); - actions.dragAndDropBy(img, Integer.MAX_VALUE, Integer.MAX_VALUE).perform(); - fail("These coordinates are outside the page - expected to fail."); - } catch (MoveTargetOutOfBoundsException expected) { - // Release mouse button - move was interrupted in the middle. - new Actions(driver).release().perform(); - } + // Release mouse button - move was interrupted in the middle. + new Actions(driver).release().perform(); } @NoDriverAfterTest diff --git a/java/test/org/openqa/selenium/javascript/ClosureTestStatement.java b/java/test/org/openqa/selenium/javascript/ClosureTestStatement.java index 05541d382ec18..7c81ef9246260 100644 --- a/java/test/org/openqa/selenium/javascript/ClosureTestStatement.java +++ b/java/test/org/openqa/selenium/javascript/ClosureTestStatement.java @@ -17,8 +17,6 @@ package org.openqa.selenium.javascript; -import static org.junit.jupiter.api.Assertions.fail; - import com.google.common.base.Stopwatch; import java.net.URL; import java.util.concurrent.TimeUnit; @@ -29,7 +27,6 @@ import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebDriverException; class ClosureTestStatement { @@ -70,11 +67,7 @@ public void evaluate() throws Throwable { // Avoid Safari JS leak between tests. executor.executeScript("if (window && window.top) window.top.G_testRunner = null"); - try { - driver.get(testUrl.toString()); - } catch (WebDriverException e) { - fail("Test failed to load: " + e.getMessage()); - } + driver.get(testUrl.toString()); while (!getBoolean(executor, Query.IS_FINISHED)) { long elapsedTime = stopwatch.elapsed(TimeUnit.SECONDS); diff --git a/java/test/org/openqa/selenium/json/JsonOutputTest.java b/java/test/org/openqa/selenium/json/JsonOutputTest.java index 10d246d431b8f..d567e834c06e5 100644 --- a/java/test/org/openqa/selenium/json/JsonOutputTest.java +++ b/java/test/org/openqa/selenium/json/JsonOutputTest.java @@ -666,7 +666,7 @@ void shouldNotWriteOptionalsThatAreNotPresentToAList() { JsonArray converted = JsonParser.parseString(json).getAsJsonArray(); - assertThat(converted.size()).isEqualTo(1); + assertThat(converted).hasSize(1); assertThat(converted.get(0).getAsString()).isEqualTo("cheese"); } diff --git a/java/test/org/openqa/selenium/json/JsonTest.java b/java/test/org/openqa/selenium/json/JsonTest.java index 3c9be8c689b12..5e6a2eca6f6f0 100644 --- a/java/test/org/openqa/selenium/json/JsonTest.java +++ b/java/test/org/openqa/selenium/json/JsonTest.java @@ -160,7 +160,7 @@ void canPopulateAMapThatContainsNull() { String raw = "{\"foo\": null}"; Map, ?> converted = new Json().toType(raw, Map.class); - assertThat(converted.size()).isEqualTo(1); + assertThat(converted).hasSize(1); assertThat(converted.containsKey("foo")).isTrue(); assertThat(converted.get("foo")).isNull(); } diff --git a/java/test/org/openqa/selenium/netty/server/NettyServerTest.java b/java/test/org/openqa/selenium/netty/server/NettyServerTest.java index fd110c233e80e..d911e7cc8f875 100644 --- a/java/test/org/openqa/selenium/netty/server/NettyServerTest.java +++ b/java/test/org/openqa/selenium/netty/server/NettyServerTest.java @@ -78,11 +78,11 @@ void ensureMultipleCallsWorkAsExpected() { HttpResponse res = client.execute(new HttpRequest(GET, "/does-not-matter")); outputHeaders(res); - assertThat(count.get()).isEqualTo(1); + assertThat(count).hasValue(1); client.execute(new HttpRequest(GET, "/does-not-matter")); outputHeaders(res); - assertThat(count.get()).isEqualTo(2); + assertThat(count).hasValue(2); } @Test diff --git a/java/test/org/openqa/selenium/print/PrintOptionsTest.java b/java/test/org/openqa/selenium/print/PrintOptionsTest.java index fa8f5e6808c43..684ce30bcdc5d 100644 --- a/java/test/org/openqa/selenium/print/PrintOptionsTest.java +++ b/java/test/org/openqa/selenium/print/PrintOptionsTest.java @@ -64,7 +64,7 @@ void toMapContainsProperKey() { printOptions.setPageRanges("1-2"); Map map = printOptions.toMap(); - assertThat(map.size()).isEqualTo(7); + assertThat(map).hasSize(7); assertThat(map.containsKey("page")).isTrue(); assertThat(map.containsKey("orientation")).isTrue(); assertThat(map.containsKey("scale")).isTrue(); @@ -74,8 +74,8 @@ void toMapContainsProperKey() { assertThat(map.containsKey("margin")).isTrue(); Map margin = (Map) map.get("margin"); - assertThat(margin.size()).isEqualTo(4); + assertThat(margin).hasSize(4); Map page = (Map) map.get("page"); - assertThat(page.size()).isEqualTo(2); + assertThat(page).hasSize(2); } } diff --git a/java/test/org/openqa/selenium/remote/RemotableByTest.java b/java/test/org/openqa/selenium/remote/RemotableByTest.java index df526e46efa0d..9369dc1581265 100644 --- a/java/test/org/openqa/selenium/remote/RemotableByTest.java +++ b/java/test/org/openqa/selenium/remote/RemotableByTest.java @@ -17,12 +17,12 @@ package org.openqa.selenium.remote; +import static com.google.common.collect.ImmutableMap.of; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.openqa.selenium.remote.ErrorCodes.SUCCESS_STRING; -import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.Iterator; import java.util.List; @@ -56,8 +56,7 @@ void shouldCallW3CLocatorWithW3CParameters() { }); driver.findElement(By.cssSelector("#foo")); - assertThat(parameters.get()) - .isEqualTo(ImmutableMap.of("using", "css selector", "value", "#foo")); + assertThat(parameters).hasValue(of("using", "css selector", "value", "#foo")); } @Test @@ -79,8 +78,7 @@ public List findElements(SearchContext context) { } }); - assertThat(parameters.get()) - .isEqualTo(ImmutableMap.of("using", "css selector", "value", "#foo")); + assertThat(parameters).hasValue(of("using", "css selector", "value", "#foo")); } @Test @@ -108,8 +106,7 @@ public List findElements(SearchContext context) { driver.findElement(new CustomBy()); - assertThat(parameters.get()) - .isEqualTo(ImmutableMap.of("using", "magic", "value", "abracadabra")); + assertThat(parameters).hasValue(of("using", "magic", "value", "abracadabra")); } @Test @@ -138,8 +135,7 @@ public List findElements(SearchContext context) { driver.findElement(new CustomBy()); - assertThat(parameters.get()) - .isEqualTo(ImmutableMap.of("using", "css selector", "value", "not-magic")); + assertThat(parameters).hasValue(of("using", "css selector", "value", "not-magic")); } @Test @@ -192,8 +188,7 @@ public Parameters getRemoteParameters() { driver.findElement(new CustomBy("two")); driver.findElement(new CustomBy("three")); - assertThat(parameters.get()) - .isEqualTo(ImmutableMap.of("using", "css selector", "value", "three")); + assertThat(parameters).hasValue(of("using", "css selector", "value", "three")); } private Response createResponse(Object value) { diff --git a/java/test/org/openqa/selenium/remote/RemoteWebDriverBuilderTest.java b/java/test/org/openqa/selenium/remote/RemoteWebDriverBuilderTest.java index f008d1fb5c86f..a365b9e7b9038 100644 --- a/java/test/org/openqa/selenium/remote/RemoteWebDriverBuilderTest.java +++ b/java/test/org/openqa/selenium/remote/RemoteWebDriverBuilderTest.java @@ -232,7 +232,7 @@ void ifARemoteUrlIsGivenThatIsUsedForTheSession() { }) .build(); - assertThat(seen.get()).isEqualTo(uri); + assertThat(seen).hasValue(uri); } @Test @@ -259,7 +259,7 @@ public URL getUrl() { }) .build(); - assertThat(seen.get()).isEqualTo(uri); + assertThat(seen).hasValue(uri); } @Test @@ -310,7 +310,7 @@ void shouldBeAbleToSetClientConfigDirectly() { }) .build(); - assertThat(seen.get()).isEqualTo(uri); + assertThat(seen).hasValue(uri); } @Test @@ -330,7 +330,7 @@ void shouldSetRemoteHostUriOnClientConfigIfSet() { }) .build(); - assertThat(seen.get()).isEqualTo(uri); + assertThat(seen).hasValue(uri); } @Test diff --git a/java/test/org/openqa/selenium/remote/WebElementToJsonConverterTest.java b/java/test/org/openqa/selenium/remote/WebElementToJsonConverterTest.java index 5aa83cdbde6c1..5a9e1ce7e4201 100644 --- a/java/test/org/openqa/selenium/remote/WebElementToJsonConverterTest.java +++ b/java/test/org/openqa/selenium/remote/WebElementToJsonConverterTest.java @@ -158,7 +158,7 @@ void convertsANestedMap() { assertThat(map.get("nested")).isInstanceOf(Map.class); map = (Map) map.get("nested"); - assertThat(map.size()).isEqualTo(1); + assertThat(map).hasSize(1); assertThat(map.get("bugs")).isEqualTo("bunny"); } @@ -190,7 +190,7 @@ void convertsAMapWithAWebElement() { assertThat(value).isInstanceOf(Map.class); Map map = (Map) value; - assertThat(map.size()).isEqualTo(1); + assertThat(map).hasSize(1); assertIsWebElementObject(map.get("one"), "abc123"); } diff --git a/java/test/org/openqa/selenium/remote/http/FilterTest.java b/java/test/org/openqa/selenium/remote/http/FilterTest.java index 6c5aff54a6571..e24732a4c400f 100644 --- a/java/test/org/openqa/selenium/remote/http/FilterTest.java +++ b/java/test/org/openqa/selenium/remote/http/FilterTest.java @@ -113,9 +113,9 @@ void eachFilterShouldOnlyBeCalledOnce() { root.execute(new HttpRequest(GET, "/cheese")); - assertThat(rootCalls.get()).isEqualTo(1); - assertThat(filterOneCount.get()).isEqualTo(1); - assertThat(filterTwoCount.get()).isEqualTo(1); + assertThat(rootCalls).hasValue(1); + assertThat(filterOneCount).hasValue(1); + assertThat(filterTwoCount).hasValue(1); } @Test diff --git a/java/test/org/openqa/selenium/remote/http/PrefixedRouteTest.java b/java/test/org/openqa/selenium/remote/http/PrefixedRouteTest.java index 834e4745b97da..c7a5d51c0efd2 100644 --- a/java/test/org/openqa/selenium/remote/http/PrefixedRouteTest.java +++ b/java/test/org/openqa/selenium/remote/http/PrefixedRouteTest.java @@ -17,11 +17,11 @@ package org.openqa.selenium.remote.http; +import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.openqa.selenium.remote.http.HttpMethod.GET; -import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Tag; @@ -89,8 +89,8 @@ void pathWhichDoesMatchHasPrefixAsAttributeWhenHandling() { route.execute(new HttpRequest(GET, "/cheese/and/peas")); - assertThat(path.get()).isEqualTo("/and/peas"); - assertThat(parts.get()).isEqualTo(singletonList("/cheese")); + assertThat(path).hasValue("/and/peas"); + assertThat(parts).hasValue(singletonList("/cheese")); } @Test @@ -115,7 +115,7 @@ void nestingPrefixesAlsoCausesPathStoredInAttributeToBeExtended() { route.execute(new HttpRequest(GET, "/cheese/and/peas")); - assertThat(path.get()).isEqualTo("/peas"); - assertThat(parts.get()).isEqualTo(Arrays.asList("/cheese", "/and")); + assertThat(path).hasValue("/peas"); + assertThat(parts).hasValue(asList("/cheese", "/and")); } } diff --git a/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java b/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java index a2fd87ccb020e..7c0ec902a90db 100644 --- a/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java +++ b/java/test/org/openqa/selenium/remote/http/RetryRequestTest.java @@ -169,7 +169,7 @@ void shouldBeAbleToHandleARequest() { assertThat(response).extracting(HttpResponse::getStatus).isEqualTo(HTTP_OK); - assertThat(count.get()).isEqualTo(1); + assertThat(count).hasValue(1); server.stop(); } @@ -194,7 +194,7 @@ void shouldBeAbleToRetryARequestOnInternalServerError() { HttpResponse response = client.execute(request); assertThat(response).extracting(HttpResponse::getStatus).isEqualTo(HTTP_OK); - assertThat(count.get()).isEqualTo(3); + assertThat(count).hasValue(3); server.stop(); } @@ -240,7 +240,7 @@ void shouldNotRetryRequestOnInternalServerErrorWithContent() { HttpResponse response = client.execute(request); assertThat(response).extracting(HttpResponse::getStatus).isEqualTo(HTTP_INTERNAL_ERROR); - assertThat(count.get()).isEqualTo(1); + assertThat(count).hasValue(1); server.stop(); } @@ -267,7 +267,7 @@ void shouldRetryRequestOnServerUnavailableError() { new HttpRequest(GET, String.format(REQUEST_PATH, uri.getHost(), uri.getPort())); HttpResponse response = client.execute(request); assertThat(response).extracting(HttpResponse::getStatus).isEqualTo(HTTP_OK); - assertThat(count.get()).isEqualTo(3); + assertThat(count).hasValue(3); server.stop(); } @@ -291,7 +291,7 @@ void shouldGetTheErrorResponseOnServerUnavailableError() { HttpResponse response = client.execute(request); assertThat(response).extracting(HttpResponse::getStatus).isEqualTo(HTTP_UNAVAILABLE); - assertThat(count.get()).isEqualTo(3); + assertThat(count).hasValue(3); server.stop(); } @@ -314,7 +314,7 @@ void shouldBeAbleToRetryARequestOnConnectionFailure() { HttpResponse response = handler.execute(request); assertThat(response).extracting(HttpResponse::getStatus).isEqualTo(HTTP_OK); - assertThat(count.get()).isEqualTo(3); + assertThat(count).hasValue(3); } @Test @@ -334,7 +334,7 @@ void shouldRethrowOnConnectFailure() { Assertions.assertThrows( UncheckedIOException.class, () -> handler.execute(new HttpRequest(GET, "/"))); assertThat(thrown).isSameAs(lastThrown.get()); - assertThat(count.get()).isEqualTo(4); + assertThat(count).hasValue(4); } @Test @@ -351,6 +351,6 @@ void shouldDeliverUnmodifiedServerErrors() { }); assertThat(handler.execute(new HttpRequest(GET, "/"))).isSameAs(lastResponse.get()); - assertThat(count.get()).isEqualTo(3); + assertThat(count).hasValue(3); } } diff --git a/java/test/org/openqa/selenium/remote/internal/WebSocketTestBase.java b/java/test/org/openqa/selenium/remote/internal/WebSocketTestBase.java index de71f4489cb9a..754126ba27576 100644 --- a/java/test/org/openqa/selenium/remote/internal/WebSocketTestBase.java +++ b/java/test/org/openqa/selenium/remote/internal/WebSocketTestBase.java @@ -111,7 +111,7 @@ public void onText(CharSequence data) { assertThat(latch.await(10, SECONDS)).isTrue(); } - assertThat(message.get()).isEqualTo("Hello, World!"); + assertThat(message).hasValue("Hello, World!"); } @Test @@ -134,7 +134,7 @@ public void onBinary(byte[] data) { assertThat(latch.await(10, SECONDS)).isTrue(); } - assertThat(message.get()).isEqualTo("brie".getBytes(UTF_8)); + assertThat(message).hasValue("brie".getBytes(UTF_8)); } private static BaseServerOptions defaultOptions() { diff --git a/java/test/org/openqa/selenium/safari/SafariDriverTest.java b/java/test/org/openqa/selenium/safari/SafariDriverTest.java index 15118a013a6d1..f61a8c772837c 100644 --- a/java/test/org/openqa/selenium/safari/SafariDriverTest.java +++ b/java/test/org/openqa/selenium/safari/SafariDriverTest.java @@ -17,9 +17,7 @@ package org.openqa.selenium.safari; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.IOException; diff --git a/java/test/org/openqa/selenium/support/events/EventFiringDecoratorTest.java b/java/test/org/openqa/selenium/support/events/EventFiringDecoratorTest.java index 1f98f4cc2159a..5863ea926e91f 100644 --- a/java/test/org/openqa/selenium/support/events/EventFiringDecoratorTest.java +++ b/java/test/org/openqa/selenium/support/events/EventFiringDecoratorTest.java @@ -1349,6 +1349,6 @@ public void beforeAnyCall(Object target, Method method, Object[] args) { RemoteWebDriver rem = new EventFiringDecorator<>(RemoteWebDriver.class, listener).decorate(originalDriver); rem.get("http://localhost:4444"); - assertThat(invocationCount.get()).isEqualTo(1); + assertThat(invocationCount).hasValue(1); } } diff --git a/java/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java b/java/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java index d7cccb7616a38..2925f8690049f 100644 --- a/java/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java +++ b/java/test/org/openqa/selenium/support/ui/ExpectedConditionsTest.java @@ -26,6 +26,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import static org.openqa.selenium.By.cssSelector; import static org.openqa.selenium.support.ui.ExpectedConditions.and; import static org.openqa.selenium.support.ui.ExpectedConditions.attributeContains; import static org.openqa.selenium.support.ui.ExpectedConditions.attributeToBe; @@ -767,8 +768,7 @@ void waitingForSpecificNumberOfElementsMoreThanSpecifiedPositive() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))) .thenReturn(Arrays.asList(mockElement, mockElement)); - assertThat(wait.until(numberOfElementsToBeMoreThan(By.cssSelector(testSelector), 1)).size()) - .isEqualTo(2); + assertThat(wait.until(numberOfElementsToBeMoreThan(cssSelector(testSelector), 1))).hasSize(2); } @Test @@ -786,8 +786,7 @@ void waitingForSpecificNumberOfElementsLessThanSpecifiedPositive() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))) .thenReturn(singletonList(mockElement)); - assertThat(wait.until(numberOfElementsToBeLessThan(By.cssSelector(testSelector), 2)).size()) - .isEqualTo(1); + assertThat(wait.until(numberOfElementsToBeLessThan(cssSelector(testSelector), 2))).hasSize(1); } @Test @@ -795,8 +794,7 @@ void waitingForSpecificNumberOfElementsPositive() { String testSelector = "testSelector"; when(mockDriver.findElements(By.cssSelector(testSelector))) .thenReturn(Arrays.asList(mockElement, mockElement)); - assertThat(wait.until(numberOfElementsToBe(By.cssSelector(testSelector), 2)).size()) - .isEqualTo(2); + assertThat(wait.until(numberOfElementsToBe(cssSelector(testSelector), 2))).hasSize(2); } @Test diff --git a/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java b/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java index 38c5938d706e0..0045ab67ae507 100644 --- a/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java +++ b/java/test/org/openqa/selenium/virtualauthenticator/VirtualAuthenticatorTest.java @@ -191,7 +191,7 @@ void testAddNonResidentCredential() { authenticator.addCredential(credential); List credentialList = authenticator.getCredentials(); - assertThat(credentialList.size()).isEqualTo(1); + assertThat(credentialList).hasSize(1); Credential retrievedCredential = credentialList.get(0); assertThat(retrievedCredential.getId()).isEqualTo(credentialId); } @@ -294,7 +294,7 @@ void testGetCredentials() { // Retrieve the two credentials. List credentials = authenticator.getCredentials(); - assertThat(credentials.size()).isEqualTo(2); + assertThat(credentials).hasSize(2); Credential credential1 = null; Credential credential2 = null; @@ -304,7 +304,7 @@ void testGetCredentials() { } else if (Arrays.equals(credential.getId(), credential2Id)) { credential2 = credential; } else { - fail("Unrecognized credential id"); + fail("Unrecognized credential id: " + Arrays.toString(credential.getId())); } }