diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 57ed219ec..145292c6c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,6 @@ name: Continuous Integration -on: [push] +on: [push, pull_request] jobs: Build: @@ -12,6 +12,8 @@ jobs: with: java-version: '17' distribution: 'temurin' + - name: Maven Version + run: mvn --version - name: Build run: mvn -DskipTests package --file pom.xml @@ -25,5 +27,7 @@ jobs: with: java-version: '17' distribution: 'temurin' + - name: Maven Version + run: mvn --version - name: Test run: mvn test --file pom.xml diff --git a/build.gradle b/build.gradle index bebbfe7a1..3c4723581 100644 --- a/build.gradle +++ b/build.gradle @@ -35,7 +35,7 @@ publishing { } dependencies { - implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.13' - testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.13' - testImplementation group: 'junit', name: 'junit', version: '4.13.1' + implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.15' + testImplementation group: 'org.slf4j', name: 'slf4j-simple', version: '2.0.15' + testImplementation group: 'org.junit', name: 'junit-bom', version: '5.11.4', ext: 'pom' } diff --git a/pom.xml b/pom.xml index 764962750..fa2caa283 100644 --- a/pom.xml +++ b/pom.xml @@ -10,11 +10,13 @@ A barebones WebSocket client and server implementation written 100% in Java https://github.com/TooTallNate/Java-WebSocket + 1.8 + 1.8 UTF-8 - 2.0.13 + 2.0.16 - 4.13.1 + 5.11.4 6.4.0 @@ -57,10 +59,11 @@ test - junit - junit + org.junit + junit-bom ${junit.version} - test + pom + import @@ -101,7 +104,7 @@ compile - 7 + 8 @@ -288,8 +291,8 @@ test - junit - junit + org.junit.jupiter + junit-jupiter test diff --git a/src/main/example/SSLServerLetsEncryptExample.java b/src/main/example/SSLServerLetsEncryptExample.java index a048dd2eb..95308aa99 100644 --- a/src/main/example/SSLServerLetsEncryptExample.java +++ b/src/main/example/SSLServerLetsEncryptExample.java @@ -40,7 +40,6 @@ import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; -import javax.xml.bind.DatatypeConverter; import org.java_websocket.server.DefaultSSLWebSocketServerFactory; @@ -98,7 +97,8 @@ private static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String String data = new String(pem); String[] tokens = data.split(beginDelimiter); tokens = tokens[1].split(endDelimiter); - return DatatypeConverter.parseBase64Binary(tokens[0]); + // return DatatypeConverter.parseBase64Binary(tokens[0]); + return null; } private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) diff --git a/src/main/example/simplelogger.properties b/src/main/example/simplelogger.properties index aa4322e92..794b8ad5a 100644 --- a/src/main/example/simplelogger.properties +++ b/src/main/example/simplelogger.properties @@ -1,5 +1,5 @@ org.slf4j.simpleLogger.logFile=System.out -org.slf4j.simpleLogger.defaultLogLevel=trace +org.slf4j.simpleLogger.defaultLogLevel=off org.slf4j.simpleLogger.showDateTime=true org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss.SSS org.slf4j.simpleLogger.showThreadName=false diff --git a/src/main/java/org/java_websocket/AbstractWebSocket.java b/src/main/java/org/java_websocket/AbstractWebSocket.java index bbb1dc8f0..ae9ce1824 100644 --- a/src/main/java/org/java_websocket/AbstractWebSocket.java +++ b/src/main/java/org/java_websocket/AbstractWebSocket.java @@ -201,7 +201,7 @@ protected void startConnectionLostTimer() { private void restartConnectionLostTimer() { cancelConnectionLostTimer(); connectionLostCheckerService = Executors - .newSingleThreadScheduledExecutor(new NamedThreadFactory("connectionLostChecker", daemon)); + .newSingleThreadScheduledExecutor(new NamedThreadFactory("WebSocketConnectionLostChecker", daemon)); Runnable connectionLostChecker = new Runnable() { /** diff --git a/src/test/java/org/java_websocket/AllTests.java b/src/test/java/org/java_websocket/AllTests.java deleted file mode 100644 index 7285be993..000000000 --- a/src/test/java/org/java_websocket/AllTests.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.util.ByteBufferUtilsTest.class, - org.java_websocket.util.Base64Test.class, - org.java_websocket.client.AllClientTests.class, - org.java_websocket.drafts.AllDraftTests.class, - org.java_websocket.issues.AllIssueTests.class, - org.java_websocket.exceptions.AllExceptionsTests.class, - org.java_websocket.misc.AllMiscTests.class, - org.java_websocket.protocols.AllProtocolTests.class, - org.java_websocket.framing.AllFramingTests.class -}) -/** - * Start all tests - */ -public class AllTests { - -} diff --git a/src/test/java/org/java_websocket/client/AllClientTests.java b/src/test/java/org/java_websocket/client/AllClientTests.java deleted file mode 100644 index 70006f0ac..000000000 --- a/src/test/java/org/java_websocket/client/AllClientTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.client; - - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.client.AttachmentTest.class, - org.java_websocket.client.SchemaCheckTest.class, - org.java_websocket.client.HeadersTest.class -}) -/** - * Start all tests for the client - */ -public class AllClientTests { - -} diff --git a/src/test/java/org/java_websocket/client/AttachmentTest.java b/src/test/java/org/java_websocket/client/AttachmentTest.java index 3a094816e..217bdf1b3 100644 --- a/src/test/java/org/java_websocket/client/AttachmentTest.java +++ b/src/test/java/org/java_websocket/client/AttachmentTest.java @@ -25,13 +25,14 @@ package org.java_websocket.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; import java.net.URI; import java.net.URISyntaxException; import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class AttachmentTest { diff --git a/src/test/java/org/java_websocket/client/ConnectBlockingTest.java b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java index fa7797cd8..bb4741043 100644 --- a/src/test/java/org/java_websocket/client/ConnectBlockingTest.java +++ b/src/test/java/org/java_websocket/client/ConnectBlockingTest.java @@ -4,65 +4,75 @@ import java.net.*; import java.util.Set; import java.util.concurrent.*; + import org.java_websocket.WebSocket; import org.java_websocket.handshake.*; import org.java_websocket.client.*; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.enums.ReadyState; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class ConnectBlockingTest { - @Test(timeout = 1000) - public void test_ConnectBlockingCleanup() throws Throwable { + @Test + @Timeout(1000) + public void test_ConnectBlockingCleanup() throws Throwable { + + Set threadSet1 = Thread.getAllStackTraces().keySet(); + final CountDownLatch ready = new CountDownLatch(1); + final CountDownLatch accepted = new CountDownLatch(1); + + final int port = SocketUtil.getAvailablePort(); + + /* TCP server which listens to a port, but does not answer handshake */ + Thread server = new Thread(new Runnable() { + @Override + public void run() { + try { + ServerSocket serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + ready.countDown(); + Socket clientSocket = serverSocket.accept(); + accepted.countDown(); + } catch (Throwable t) { + assertInstanceOf(InterruptedException.class, t); + } + } + }); + server.start(); + ready.await(); - Set threadSet1 = Thread.getAllStackTraces().keySet(); - final CountDownLatch ready = new CountDownLatch(1); - final CountDownLatch accepted = new CountDownLatch(1); + WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshake) { + } - final int port = SocketUtil.getAvailablePort(); + @Override + public void onClose(int code, String reason, boolean remote) { + } - /* TCP server which listens to a port, but does not answer handshake */ - Thread server = new Thread(new Runnable() { - @Override - public void run() { - try { - ServerSocket serverSocket = new ServerSocket(port); - ready.countDown(); - Socket clientSocket = serverSocket.accept(); - accepted.countDown(); - } catch (Throwable t) { - assertTrue(t instanceof InterruptedException); - } - } - }); - server.start(); - ready.await(); + @Override + public void onMessage(String message) { + } - WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshake) { - } - @Override - public void onClose(int code, String reason, boolean remote) {} - @Override - public void onMessage(String message) {} - @Override - public void onError(Exception ex) { - ex.printStackTrace(); - } - }; - boolean connected = client.connectBlocking(100, TimeUnit.MILLISECONDS); - assertEquals("TCP socket should have been accepted", 0, accepted.getCount()); - assertFalse("WebSocket should not be connected (as server didn't send handshake)", connected); + @Override + public void onError(Exception ex) { + ex.printStackTrace(); + } + }; + boolean connected = client.connectBlocking(100, TimeUnit.MILLISECONDS); + assertEquals( 0, accepted.getCount(), "TCP socket should have been accepted"); + assertFalse(connected, "WebSocket should not be connected (as server didn't send handshake)"); - server.interrupt(); - server.join(); + server.interrupt(); + server.join(); - Set threadSet2 = Thread.getAllStackTraces().keySet(); - assertEquals("no threads left over", threadSet1, threadSet2); - assertTrue("WebSocket is in closed state", client.getReadyState() == ReadyState.CLOSED || client.getReadyState() == ReadyState.NOT_YET_CONNECTED); - } + Set threadSet2 = Thread.getAllStackTraces().keySet(); + assertEquals(threadSet1, threadSet2, "no threads left over"); + assertTrue(client.getReadyState() == ReadyState.CLOSED || client.getReadyState() == ReadyState.NOT_YET_CONNECTED, "WebSocket is in closed state"); + } } diff --git a/src/test/java/org/java_websocket/client/HeadersTest.java b/src/test/java/org/java_websocket/client/HeadersTest.java index 7d31422b5..8d60cf005 100644 --- a/src/test/java/org/java_websocket/client/HeadersTest.java +++ b/src/test/java/org/java_websocket/client/HeadersTest.java @@ -25,15 +25,15 @@ package org.java_websocket.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class HeadersTest { diff --git a/src/test/java/org/java_websocket/client/SchemaCheckTest.java b/src/test/java/org/java_websocket/client/SchemaCheckTest.java index 30f13e6f9..af36e5c66 100644 --- a/src/test/java/org/java_websocket/client/SchemaCheckTest.java +++ b/src/test/java/org/java_websocket/client/SchemaCheckTest.java @@ -1,85 +1,86 @@ package org.java_websocket.client; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import java.net.URI; import java.net.URISyntaxException; -import org.java_websocket.handshake.ServerHandshake; -import org.junit.Test; - -public class SchemaCheckTest { - - @Test - public void testSchemaCheck() throws URISyntaxException { - final String[] invalidCase = { - "http://localhost:80", - "http://localhost:81", - "http://localhost", - "https://localhost:443", - "https://localhost:444", - "https://localhost", - "any://localhost", - "any://localhost:82", - }; - final Exception[] exs = new Exception[invalidCase.length]; - for (int i = 0; i < invalidCase.length; i++) { - final int finalI = i; - new WebSocketClient(new URI(invalidCase[finalI])) { - @Override - public void onOpen(ServerHandshake handshakedata) { - - } - @Override - public void onMessage(String message) { - - } - - @Override - public void onClose(int code, String reason, boolean remote) { - - } - - @Override - public void onError(Exception ex) { - exs[finalI] = ex; - } - }.run(); - } - for (Exception exception : exs) { - assertTrue(exception instanceof IllegalArgumentException); - } - final String[] validCase = { - "ws://localhost", - "ws://localhost:80", - "ws://localhost:81", - "wss://localhost", - "wss://localhost:443", - "wss://localhost:444" - }; - for (String s : validCase) { - new WebSocketClient(new URI(s)) { - @Override - public void onOpen(ServerHandshake handshakedata) { +import org.java_websocket.handshake.ServerHandshake; +import org.junit.jupiter.api.Test; - } +import static org.junit.jupiter.api.Assertions.*; - @Override - public void onMessage(String message) { +public class SchemaCheckTest { + @Test + public void testSchemaCheck() throws URISyntaxException { + final String[] invalidCase = { + "http://localhost:80", + "http://localhost:81", + "http://localhost", + "https://localhost:443", + "https://localhost:444", + "https://localhost", + "any://localhost", + "any://localhost:82", + }; + final Exception[] exs = new Exception[invalidCase.length]; + for (int i = 0; i < invalidCase.length; i++) { + final int finalI = i; + new WebSocketClient(new URI(invalidCase[finalI])) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + exs[finalI] = ex; + } + }.run(); } - - @Override - public void onClose(int code, String reason, boolean remote) { - + for (Exception exception : exs) { + assertInstanceOf(IllegalArgumentException.class, exception); } - - @Override - public void onError(Exception ex) { - assertFalse(ex instanceof IllegalArgumentException); + final String[] validCase = { + "ws://localhost", + "ws://localhost:80", + "ws://localhost:81", + "wss://localhost", + "wss://localhost:443", + "wss://localhost:444" + }; + for (String s : validCase) { + new WebSocketClient(new URI(s)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + + } + + @Override + public void onError(Exception ex) { + assertFalse(ex instanceof IllegalArgumentException); + } + }.run(); } - }.run(); } - } } diff --git a/src/test/java/org/java_websocket/drafts/AllDraftTests.java b/src/test/java/org/java_websocket/drafts/AllDraftTests.java deleted file mode 100644 index 39d2fa3fc..000000000 --- a/src/test/java/org/java_websocket/drafts/AllDraftTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.drafts; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.drafts.Draft_6455Test.class -}) -/** - * Start all tests for drafts - */ -public class AllDraftTests { - -} diff --git a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java index d272de7fe..41850b32e 100644 --- a/src/test/java/org/java_websocket/drafts/Draft_6455Test.java +++ b/src/test/java/org/java_websocket/drafts/Draft_6455Test.java @@ -25,13 +25,6 @@ package org.java_websocket.drafts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; @@ -49,7 +42,9 @@ import org.java_websocket.protocols.IProtocol; import org.java_websocket.protocols.Protocol; import org.java_websocket.util.Charsetfunctions; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class Draft_6455Test { @@ -90,33 +85,33 @@ public void testConstructor() throws Exception { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), null); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), null); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(null, Collections.emptyList()); + Draft_6455 draft_6455 = new Draft_6455(null, Collections.emptyList()); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList(), -1); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList(), -1); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } try { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList(), 0); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList(), 0); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { //Fine } - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertEquals(1, draft_6455.getKnownExtensions().size()); assertEquals(0, draft_6455.getKnownProtocols().size()); } @@ -140,13 +135,13 @@ public void testGetKnownExtensions() throws Exception { @Test public void testGetProtocol() throws Exception { - Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + Draft_6455 draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertNull(draft_6455.getProtocol()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertNull(draft_6455.getProtocol()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertNull(draft_6455.getProtocol()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertNotNull(draft_6455.getProtocol()); @@ -156,24 +151,24 @@ public void testGetProtocol() throws Exception { public void testGetKnownProtocols() throws Exception { Draft_6455 draft_6455 = new Draft_6455(); assertEquals(1, draft_6455.getKnownProtocols().size()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertEquals(0, draft_6455.getKnownProtocols().size()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals(1, draft_6455.getKnownProtocols().size()); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("test")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(2, draft_6455.getKnownProtocols().size()); } @Test public void testCopyInstance() throws Exception { Draft_6455 draft_6455 = new Draft_6455( - Collections.singletonList(new TestExtension()), - Collections.singletonList(new Protocol("chat"))); + Collections.singletonList(new TestExtension()), + Collections.singletonList(new Protocol("chat"))); Draft_6455 draftCopy = (Draft_6455) draft_6455.copyInstance(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertNotEquals(draft_6455, draftCopy); @@ -186,7 +181,7 @@ public void testCopyInstance() throws Exception { @Test public void testReset() throws Exception { Draft_6455 draft_6455 = new Draft_6455( - Collections.singletonList(new TestExtension()), 100); + Collections.singletonList(new TestExtension()), 100); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); List extensionList = new ArrayList(draft_6455.getKnownExtensions()); List protocolList = new ArrayList(draft_6455.getKnownProtocols()); @@ -212,22 +207,22 @@ public void testToString() throws Exception { draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertEquals("Draft_6455 extension: DefaultExtension protocol: max frame size: 2147483647", draft_6455.toString()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertEquals("Draft_6455 extension: DefaultExtension protocol: chat max frame size: 2147483647", draft_6455.toString()); - draft_6455 = new Draft_6455(Collections.singletonList(new TestExtension()), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.singletonList(new TestExtension()), + Collections.singletonList(new Protocol("chat"))); assertEquals("Draft_6455 extension: DefaultExtension max frame size: 2147483647", draft_6455.toString()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); assertEquals("Draft_6455 extension: TestExtension protocol: chat max frame size: 2147483647", draft_6455.toString()); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")), 10); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")), 10); assertEquals("Draft_6455 extension: DefaultExtension max frame size: 10", draft_6455.toString()); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); @@ -240,8 +235,8 @@ public void testEquals() throws Exception { Draft draft0 = new Draft_6455(); Draft draft1 = draft0.copyInstance(); assertEquals(draft0, draft1); - Draft draft2 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + Draft draft2 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); Draft draft3 = draft2.copyInstance(); assertEquals(draft2, draft3); assertEquals(draft0, draft2); @@ -281,8 +276,8 @@ public void testEquals() throws Exception { public void testHashCode() throws Exception { Draft draft0 = new Draft_6455(); Draft draft1 = draft0.copyInstance(); - Draft draft2 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + Draft draft2 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); Draft draft3 = draft2.copyInstance(); assertEquals(draft2.hashCode(), draft3.hashCode()); assertEquals(draft0.hashCode(), draft2.hashCode()); @@ -337,8 +332,8 @@ public void acceptHandshakeAsServer() throws Exception { draft_6455.acceptHandshakeAsServer(handshakedataExtension)); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension)); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); assertEquals(HandshakeState.NOT_MATCHED, @@ -348,7 +343,7 @@ public void acceptHandshakeAsServer() throws Exception { ArrayList protocols = new ArrayList(); protocols.add(new Protocol("chat")); protocols.add(new Protocol("")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedata)); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsServer(handshakedataProtocol)); assertEquals(HandshakeState.MATCHED, @@ -374,21 +369,21 @@ public void acceptHandshakeAsClient() throws Exception { assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); response.put("Sec-WebSocket-Protocol", "chat"); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("")); protocols.add(new Protocol("chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(HandshakeState.MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.emptyList()); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.emptyList()); assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); protocols.clear(); protocols.add(new Protocol("chat3")); protocols.add(new Protocol("3chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); assertEquals(HandshakeState.NOT_MATCHED, draft_6455.acceptHandshakeAsClient(request, response)); } @@ -401,28 +396,28 @@ public void postProcessHandshakeRequestAsClient() throws Exception { assertEquals("Upgrade", request.getFieldValue("Connection")); assertEquals("13", request.getFieldValue("Sec-WebSocket-Version")); assertTrue(request.hasFieldValue("Sec-WebSocket-Key")); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Protocol")); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); request = new HandshakeImpl1Client(); draft_6455.postProcessHandshakeRequestAsClient(request); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); assertEquals("chat", request.getFieldValue("Sec-WebSocket-Protocol")); protocols.add(new Protocol("chat2")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); request = new HandshakeImpl1Client(); draft_6455.postProcessHandshakeRequestAsClient(request); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); assertEquals("chat, chat2", request.getFieldValue("Sec-WebSocket-Protocol")); protocols.clear(); protocols.add(new Protocol("")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); request = new HandshakeImpl1Client(); draft_6455.postProcessHandshakeRequestAsClient(request); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Extensions")); - assertTrue(!request.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(request.hasFieldValue("Sec-WebSocket-Protocol")); } @Test @@ -439,66 +434,66 @@ public void postProcessHandshakeResponseAsServer() throws Exception { assertEquals("TooTallNate Java-WebSocket", response.getFieldValue("Server")); assertEquals("upgrade", response.getFieldValue("Connection")); assertEquals("websocket", response.getFieldValue("Upgrade")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedata); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedataProtocol); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedataExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); - draft_6455 = new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat"))); + draft_6455 = new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat"))); draft_6455.acceptHandshakeAsServer(handshakedataProtocol); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("chat", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("chat", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); ArrayList protocols = new ArrayList(); protocols.add(new Protocol("test")); protocols.add(new Protocol("chat")); - draft_6455 = new Draft_6455(Collections.emptyList(), protocols); + draft_6455 = new Draft_6455(Collections.emptyList(), protocols); draft_6455.acceptHandshakeAsServer(handshakedataProtocol); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("test", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Protocol")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); response = new HandshakeImpl1Server(); draft_6455.reset(); draft_6455.acceptHandshakeAsServer(handshakedataProtocolExtension); draft_6455.postProcessHandshakeResponseAsServer(request, response); assertEquals("test", response.getFieldValue("Sec-WebSocket-Protocol")); - assertTrue(!response.hasFieldValue("Sec-WebSocket-Extensions")); + assertFalse(response.hasFieldValue("Sec-WebSocket-Extensions")); // issue #1053 : check the exception - missing Sec-WebSocket-Key response = new HandshakeImpl1Server(); @@ -552,7 +547,7 @@ public void createFramesText() throws Exception { } - private class TestExtension extends DefaultExtension { + private static class TestExtension extends DefaultExtension { @Override public int hashCode() { diff --git a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java b/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java deleted file mode 100644 index f0e121a8d..000000000 --- a/src/test/java/org/java_websocket/exceptions/AllExceptionsTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.exceptions; - - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.exceptions.IncompleteExceptionTest.class, - org.java_websocket.exceptions.IncompleteHandshakeExceptionTest.class, - org.java_websocket.exceptions.InvalidDataExceptionTest.class, - org.java_websocket.exceptions.InvalidEncodingExceptionTest.class, - org.java_websocket.exceptions.InvalidFrameExceptionTest.class, - org.java_websocket.exceptions.InvalidHandshakeExceptionTest.class, - org.java_websocket.exceptions.LimitExceededExceptionTest.class, - org.java_websocket.exceptions.NotSendableExceptionTest.class, - org.java_websocket.exceptions.WebsocketNotConnectedExceptionTest.class -}) -/** - * Start all tests for the exceptions - */ -public class AllExceptionsTests { - -} diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java index 9a9916dea..de831c393 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteExceptionTest.java @@ -25,9 +25,9 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the IncompleteException class @@ -37,6 +37,6 @@ public class IncompleteExceptionTest { @Test public void testConstructor() { IncompleteException incompleteException = new IncompleteException(42); - assertEquals("The argument should be set", 42, incompleteException.getPreferredSize()); + assertEquals(42, incompleteException.getPreferredSize(), "The argument should be set"); } } diff --git a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java index 9cf1829fd..0506c1530 100644 --- a/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/IncompleteHandshakeExceptionTest.java @@ -25,9 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the IncompleteHandshakeException class @@ -38,8 +39,8 @@ public class IncompleteHandshakeExceptionTest { public void testConstructor() { IncompleteHandshakeException incompleteHandshakeException = new IncompleteHandshakeException( 42); - assertEquals("The argument should be set", 42, incompleteHandshakeException.getPreferredSize()); + assertEquals( 42, incompleteHandshakeException.getPreferredSize(), "The argument should be set"); incompleteHandshakeException = new IncompleteHandshakeException(); - assertEquals("The default has to be 0", 0, incompleteHandshakeException.getPreferredSize()); + assertEquals(0, incompleteHandshakeException.getPreferredSize(), "The default has to be 0"); } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java index c9c4e5849..332f8fd22 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidDataExceptionTest.java @@ -25,9 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the InvalidDataException class @@ -37,19 +38,19 @@ public class InvalidDataExceptionTest { @Test public void testConstructor() { InvalidDataException invalidDataException = new InvalidDataException(42); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); + assertEquals(42, invalidDataException.getCloseCode(), "The close code has to be the argument"); invalidDataException = new InvalidDataException(42, "Message"); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidDataException.getMessage()); + assertEquals(42, invalidDataException.getCloseCode(), "The close code has to be the argument"); + assertEquals( "Message", + invalidDataException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); invalidDataException = new InvalidDataException(42, "Message", e); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidDataException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); + assertEquals( 42, invalidDataException.getCloseCode(), "The close code has to be the argument"); + assertEquals( "Message", + invalidDataException.getMessage(), "The message has to be the argument"); + assertEquals(e, invalidDataException.getCause(), "The throwable has to be the argument"); invalidDataException = new InvalidDataException(42, e); - assertEquals("The close code has to be the argument", 42, invalidDataException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidDataException.getCause()); + assertEquals(42, invalidDataException.getCloseCode(), "The close code has to be the argument"); + assertEquals(e, invalidDataException.getCause(), "The throwable has to be the argument"); } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java index 96e005be5..2edb0ad31 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidEncodingExceptionTest.java @@ -25,11 +25,12 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * JUnit Test for the InvalidEncodingException class @@ -41,8 +42,8 @@ public void testConstructor() { UnsupportedEncodingException unsupportedEncodingException = new UnsupportedEncodingException(); InvalidEncodingException invalidEncodingException = new InvalidEncodingException( unsupportedEncodingException); - assertEquals("The argument has to be the provided exception", unsupportedEncodingException, - invalidEncodingException.getEncodingException()); + assertEquals(unsupportedEncodingException, + invalidEncodingException.getEncodingException(), "The argument has to be the provided exception"); try { invalidEncodingException = new InvalidEncodingException(null); fail("IllegalArgumentException should be thrown"); diff --git a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java index 27a2e0dbd..359e6d69b 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidFrameExceptionTest.java @@ -25,10 +25,11 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; import org.java_websocket.framing.CloseFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the InvalidFrameException class @@ -38,30 +39,29 @@ public class InvalidFrameExceptionTest { @Test public void testConstructor() { InvalidFrameException invalidFrameException = new InvalidFrameException(); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); + assertEquals( CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); invalidFrameException = new InvalidFrameException("Message"); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidFrameException.getMessage()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals("Message", + invalidFrameException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); invalidFrameException = new InvalidFrameException("Message", e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidFrameException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals("Message", + invalidFrameException.getMessage(), "The message has to be the argument"); + assertEquals(e, invalidFrameException.getCause(), "The throwable has to be the argument"); invalidFrameException = new InvalidFrameException(e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidFrameException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidFrameException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidFrameException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals(e, invalidFrameException.getCause(), "The throwable has to be the argument"); } @Test public void testExtends() { InvalidFrameException invalidFrameException = new InvalidFrameException(); - assertEquals("InvalidFrameException must extend InvalidDataException", true, - invalidFrameException instanceof InvalidDataException); + assertInstanceOf(InvalidDataException.class, invalidFrameException, "InvalidFrameException must extend InvalidDataException"); } } diff --git a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java index da9fdc94b..0b8863c0b 100644 --- a/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/InvalidHandshakeExceptionTest.java @@ -25,10 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; - import org.java_websocket.framing.CloseFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the InvalidHandshakeException class @@ -38,31 +38,30 @@ public class InvalidHandshakeExceptionTest { @Test public void testConstructor() { InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); + assertEquals( CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); invalidHandshakeException = new InvalidHandshakeException("Message"); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidHandshakeException.getMessage()); + assertEquals( CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals( "Message", + invalidHandshakeException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); invalidHandshakeException = new InvalidHandshakeException("Message", e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - invalidHandshakeException.getMessage()); - assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals( "Message", + invalidHandshakeException.getMessage(), "The message has to be the argument"); + assertEquals(e, invalidHandshakeException.getCause(), "The throwable has to be the argument"); invalidHandshakeException = new InvalidHandshakeException(e); - assertEquals("The close code has to be PROTOCOL_ERROR", CloseFrame.PROTOCOL_ERROR, - invalidHandshakeException.getCloseCode()); - assertEquals("The throwable has to be the argument", e, invalidHandshakeException.getCause()); + assertEquals(CloseFrame.PROTOCOL_ERROR, + invalidHandshakeException.getCloseCode(), "The close code has to be PROTOCOL_ERROR"); + assertEquals(e, invalidHandshakeException.getCause(), "The throwable has to be the argument"); } @Test public void testExtends() { InvalidHandshakeException invalidHandshakeException = new InvalidHandshakeException(); - assertEquals("InvalidHandshakeException must extend InvalidDataException", true, - invalidHandshakeException instanceof InvalidDataException); + assertInstanceOf(InvalidDataException.class, invalidHandshakeException, "InvalidHandshakeException must extend InvalidDataException"); } } diff --git a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java index 4cc6ca9a6..1677da7b0 100644 --- a/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/LimitExceededExceptionTest.java @@ -25,10 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; - import org.java_websocket.framing.CloseFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the InvalidEncodingException class @@ -38,20 +38,19 @@ public class LimitExceededExceptionTest { @Test public void testConstructor() { LimitExceededException limitExceededException = new LimitExceededException(); - assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, - limitExceededException.getCloseCode()); - assertEquals("The message has to be empty", null, limitExceededException.getMessage()); + assertEquals(CloseFrame.TOOBIG, + limitExceededException.getCloseCode(), "The close code has to be TOOBIG"); + assertNull(limitExceededException.getMessage(), "The message has to be empty"); limitExceededException = new LimitExceededException("Message"); - assertEquals("The close code has to be TOOBIG", CloseFrame.TOOBIG, - limitExceededException.getCloseCode()); - assertEquals("The message has to be the argument", "Message", - limitExceededException.getMessage()); + assertEquals(CloseFrame.TOOBIG, + limitExceededException.getCloseCode(), "The close code has to be TOOBIG"); + assertEquals( "Message", + limitExceededException.getMessage(), "The message has to be the argument"); } @Test public void testExtends() { LimitExceededException limitExceededException = new LimitExceededException(); - assertEquals("LimitExceededException must extend InvalidDataException", true, - limitExceededException instanceof InvalidDataException); + assertInstanceOf(InvalidDataException.class, limitExceededException, "LimitExceededException must extend InvalidDataException"); } } diff --git a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java index 0fb2440fd..044e84d2c 100644 --- a/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/NotSendableExceptionTest.java @@ -25,9 +25,9 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * JUnit Test for the NotSendableException class @@ -37,14 +37,14 @@ public class NotSendableExceptionTest { @Test public void testConstructor() { NotSendableException notSendableException = new NotSendableException("Message"); - assertEquals("The message has to be the argument", "Message", - notSendableException.getMessage()); + assertEquals("Message", + notSendableException.getMessage(), "The message has to be the argument"); Exception e = new Exception(); notSendableException = new NotSendableException(e); - assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); + assertEquals( e, notSendableException.getCause(), "The throwable has to be the argument"); notSendableException = new NotSendableException("Message", e); - assertEquals("The message has to be the argument", "Message", - notSendableException.getMessage()); - assertEquals("The throwable has to be the argument", e, notSendableException.getCause()); + assertEquals("Message", + notSendableException.getMessage(), "The message has to be the argument"); + assertEquals(e, notSendableException.getCause(), "The throwable has to be the argument"); } } diff --git a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java index e163b2260..3f21c4460 100644 --- a/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java +++ b/src/test/java/org/java_websocket/exceptions/WebsocketNotConnectedExceptionTest.java @@ -25,9 +25,10 @@ package org.java_websocket.exceptions; -import static org.junit.Assert.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * JUnit Test for the WebsocketNotConnectedException class diff --git a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java b/src/test/java/org/java_websocket/extensions/AllExtensionTests.java deleted file mode 100644 index 3cbf552e6..000000000 --- a/src/test/java/org/java_websocket/extensions/AllExtensionTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.extensions; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.extensions.DefaultExtensionTest.class, - org.java_websocket.extensions.CompressionExtensionTest.class -}) -/** - * Start all tests for extensions - */ -public class AllExtensionTests { - -} diff --git a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java index 946e28ce7..74b8e3fb1 100644 --- a/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/CompressionExtensionTest.java @@ -1,10 +1,11 @@ package org.java_websocket.extensions; -import static org.junit.Assert.fail; import org.java_websocket.framing.PingFrame; import org.java_websocket.framing.TextFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; public class CompressionExtensionTest { diff --git a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java index 6d373f15f..e4b29907d 100644 --- a/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/DefaultExtensionTest.java @@ -25,129 +25,127 @@ package org.java_websocket.extensions; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.nio.ByteBuffer; + import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.TextFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class DefaultExtensionTest { - @Test - public void testDecodeFrame() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); - defaultExtension.decodeFrame(binaryFrame); - assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); - } - - @Test - public void testEncodeFrame() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - BinaryFrame binaryFrame = new BinaryFrame(); - binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); - defaultExtension.encodeFrame(binaryFrame); - assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); - } - - @Test - public void testAcceptProvidedExtensionAsServer() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test, ASDC, as, ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("ASDC, as,ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsServer("permessage-deflate")); - } - - @Test - public void testAcceptProvidedExtensionAsClient() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test, ASDC, as, ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("ASDC, as,ad")); - assertTrue(defaultExtension.acceptProvidedExtensionAsClient("permessage-deflate")); - } - - @Test - public void testIsFrameValid() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - TextFrame textFrame = new TextFrame(); - try { - defaultExtension.isFrameValid(textFrame); - } catch (Exception e) { - fail("This frame is valid"); + @Test + public void testDecodeFrame() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); + defaultExtension.decodeFrame(binaryFrame); + assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); + } + + @Test + public void testEncodeFrame() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + BinaryFrame binaryFrame = new BinaryFrame(); + binaryFrame.setPayload(ByteBuffer.wrap("test".getBytes())); + defaultExtension.encodeFrame(binaryFrame); + assertEquals(ByteBuffer.wrap("test".getBytes()), binaryFrame.getPayloadData()); + } + + @Test + public void testAcceptProvidedExtensionAsServer() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("Test, ASDC, as, ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("ASDC, as,ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsServer("permessage-deflate")); + } + + @Test + public void testAcceptProvidedExtensionAsClient() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("Test, ASDC, as, ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("ASDC, as,ad")); + assertTrue(defaultExtension.acceptProvidedExtensionAsClient("permessage-deflate")); + } + + @Test + public void testIsFrameValid() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + TextFrame textFrame = new TextFrame(); + try { + defaultExtension.isFrameValid(textFrame); + } catch (Exception e) { + fail("This frame is valid"); + } + textFrame.setRSV1(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV1(false); + textFrame.setRSV2(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + textFrame.setRSV2(false); + textFrame.setRSV3(true); + try { + defaultExtension.isFrameValid(textFrame); + fail("This frame is not valid"); + } catch (Exception e) { + // + } + } + + @Test + public void testGetProvidedExtensionAsClient() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("", defaultExtension.getProvidedExtensionAsClient()); + } + + @Test + public void testGetProvidedExtensionAsServer() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("", defaultExtension.getProvidedExtensionAsServer()); } - textFrame.setRSV1(true); - try { - defaultExtension.isFrameValid(textFrame); - fail("This frame is not valid"); - } catch (Exception e) { - // + + @Test + public void testCopyInstance() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + IExtension extensionCopy = defaultExtension.copyInstance(); + assertEquals(defaultExtension, extensionCopy); } - textFrame.setRSV1(false); - textFrame.setRSV2(true); - try { - defaultExtension.isFrameValid(textFrame); - fail("This frame is not valid"); - } catch (Exception e) { - // + + @Test + public void testToString() throws Exception { + DefaultExtension defaultExtension = new DefaultExtension(); + assertEquals("DefaultExtension", defaultExtension.toString()); } - textFrame.setRSV2(false); - textFrame.setRSV3(true); - try { - defaultExtension.isFrameValid(textFrame); - fail("This frame is not valid"); - } catch (Exception e) { - // + + @Test + public void testHashCode() throws Exception { + DefaultExtension defaultExtension0 = new DefaultExtension(); + DefaultExtension defaultExtension1 = new DefaultExtension(); + assertEquals(defaultExtension0.hashCode(), defaultExtension1.hashCode()); + } + + @Test + public void testEquals() throws Exception { + DefaultExtension defaultExtension0 = new DefaultExtension(); + DefaultExtension defaultExtension1 = new DefaultExtension(); + assertEquals(defaultExtension0, defaultExtension1); + assertNotEquals(null, defaultExtension0); + assertNotEquals(defaultExtension0, new Object()); } - } - - @Test - public void testGetProvidedExtensionAsClient() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals("", defaultExtension.getProvidedExtensionAsClient()); - } - - @Test - public void testGetProvidedExtensionAsServer() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals("", defaultExtension.getProvidedExtensionAsServer()); - } - - @Test - public void testCopyInstance() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - IExtension extensionCopy = defaultExtension.copyInstance(); - assertEquals(defaultExtension, extensionCopy); - } - - @Test - public void testToString() throws Exception { - DefaultExtension defaultExtension = new DefaultExtension(); - assertEquals("DefaultExtension", defaultExtension.toString()); - } - - @Test - public void testHashCode() throws Exception { - DefaultExtension defaultExtension0 = new DefaultExtension(); - DefaultExtension defaultExtension1 = new DefaultExtension(); - assertEquals(defaultExtension0.hashCode(), defaultExtension1.hashCode()); - } - - @Test - public void testEquals() throws Exception { - DefaultExtension defaultExtension0 = new DefaultExtension(); - DefaultExtension defaultExtension1 = new DefaultExtension(); - assertEquals(defaultExtension0, defaultExtension1); - assertFalse(defaultExtension0.equals(null)); - assertFalse(defaultExtension0.equals(new Object())); - } } \ No newline at end of file diff --git a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java index a4e2c3661..5a86648f3 100644 --- a/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java +++ b/src/test/java/org/java_websocket/extensions/PerMessageDeflateExtensionTest.java @@ -1,11 +1,5 @@ package org.java_websocket.extensions; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.nio.ByteBuffer; import java.util.Arrays; import java.util.zip.Deflater; @@ -14,7 +8,9 @@ import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.TextFrame; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class PerMessageDeflateExtensionTest { diff --git a/src/test/java/org/java_websocket/framing/AllFramingTests.java b/src/test/java/org/java_websocket/framing/AllFramingTests.java deleted file mode 100644 index 24265d8eb..000000000 --- a/src/test/java/org/java_websocket/framing/AllFramingTests.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.framing; - - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.framing.BinaryFrameTest.class, - org.java_websocket.framing.PingFrameTest.class, - org.java_websocket.framing.PongFrameTest.class, - org.java_websocket.framing.CloseFrameTest.class, - org.java_websocket.framing.TextFrameTest.class, - org.java_websocket.framing.ContinuousFrameTest.class, - org.java_websocket.framing.FramedataImpl1Test.class -}) -/** - * Start all tests for frames - */ -public class AllFramingTests { - -} diff --git a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java index a14e4ef25..92a839717 100644 --- a/src/test/java/org/java_websocket/framing/BinaryFrameTest.java +++ b/src/test/java/org/java_websocket/framing/BinaryFrameTest.java @@ -25,12 +25,12 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the BinaryFrame class @@ -40,13 +40,13 @@ public class BinaryFrameTest { @Test public void testConstructor() { BinaryFrame frame = new BinaryFrame(); - assertEquals("Opcode must be equal", Opcode.BINARY, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.BINARY, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals(0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -57,7 +57,7 @@ public void testConstructor() { @Test public void testExtends() { BinaryFrame frame = new BinaryFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + assertInstanceOf(DataFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/framing/CloseFrameTest.java b/src/test/java/org/java_websocket/framing/CloseFrameTest.java index 4000b2c9d..b20224634 100644 --- a/src/test/java/org/java_websocket/framing/CloseFrameTest.java +++ b/src/test/java/org/java_websocket/framing/CloseFrameTest.java @@ -25,223 +25,222 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the CloseFrame class */ public class CloseFrameTest { - @Test - public void testConstructor() { - CloseFrame frame = new CloseFrame(); - assertEquals("Opcode must be equal", Opcode.CLOSING, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be 2 (close code)", 2, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); + @Test + public void testConstructor() { + CloseFrame frame = new CloseFrame(); + assertEquals(Opcode.CLOSING, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 2, frame.getPayloadData().capacity(), "Payload must be 2 (close code)"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } } - } - @Test - public void testExtends() { - CloseFrame frame = new CloseFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } + @Test + public void testExtends() { + CloseFrame frame = new CloseFrame(); + assertInstanceOf(ControlFrame.class, frame, "Frame must extend dataframe"); + } - @Test - public void testToString() { - CloseFrame frame = new CloseFrame(); - String frameString = frame.toString(); - frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); - assertEquals("Frame toString must include a close code", - "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", - frameString); - } + @Test + public void testToString() { + CloseFrame frame = new CloseFrame(); + String frameString = frame.toString(); + frameString = frameString.replaceAll("payload:(.*)}", "payload: *}"); + assertEquals( + "Framedata{ opcode:CLOSING, fin:true, rsv1:false, rsv2:false, rsv3:false, payload length:[pos:0, len:2], payload: *}code: 1000", + frameString, "Frame toString must include a close code"); + } - @Test - public void testIsValid() { - CloseFrame frame = new CloseFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV3(false); - frame.setCode(CloseFrame.NORMAL); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.GOING_AWAY); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.PROTOCOL_ERROR); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.REFUSE); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.NOCODE); - assertEquals(0, frame.getPayloadData().capacity()); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.ABNORMAL_CLOSE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.POLICY_VALIDATION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TOOBIG); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.EXTENSION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.UNEXPECTED_CONDITION); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.SERVICE_RESTART); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TRY_AGAIN_LATER); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.BAD_GATEWAY); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setCode(CloseFrame.TLS_ERROR); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NEVER_CONNECTED); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.BUGGYCLOSE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.FLASHPOLICY); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NOCODE); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NO_UTF8); - frame.setReason(null); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine - } - frame.setCode(CloseFrame.NOCODE); - frame.setReason("Close"); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //fine + @Test + public void testIsValid() { + CloseFrame frame = new CloseFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV3(false); + frame.setCode(CloseFrame.NORMAL); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.GOING_AWAY); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.PROTOCOL_ERROR); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.REFUSE); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.NOCODE); + assertEquals(0, frame.getPayloadData().capacity()); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.ABNORMAL_CLOSE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.POLICY_VALIDATION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TOOBIG); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.EXTENSION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.UNEXPECTED_CONDITION); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.SERVICE_RESTART); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TRY_AGAIN_LATER); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.BAD_GATEWAY); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setCode(CloseFrame.TLS_ERROR); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NEVER_CONNECTED); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.BUGGYCLOSE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.FLASHPOLICY); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NO_UTF8); + frame.setReason(null); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } + frame.setCode(CloseFrame.NOCODE); + frame.setReason("Close"); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //fine + } } - } } diff --git a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java index db0f6f4b9..98c1fa266 100644 --- a/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java +++ b/src/test/java/org/java_websocket/framing/ContinuousFrameTest.java @@ -25,12 +25,13 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + /** * JUnit Test for the ContinuousFrame class @@ -40,13 +41,13 @@ public class ContinuousFrameTest { @Test public void testConstructor() { ContinuousFrame frame = new ContinuousFrame(); - assertEquals("Opcode must be equal", Opcode.CONTINUOUS, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.CONTINUOUS, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -57,7 +58,7 @@ public void testConstructor() { @Test public void testExtends() { ContinuousFrame frame = new ContinuousFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + assertInstanceOf(DataFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java index 9e7db85a3..b952091be 100644 --- a/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java +++ b/src/test/java/org/java_websocket/framing/FramedataImpl1Test.java @@ -25,13 +25,12 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the FramedataImpl1 class @@ -41,29 +40,29 @@ public class FramedataImpl1Test { @Test public void testDefaultValues() { FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); - assertEquals("Opcode must be equal", Opcode.BINARY, binary.getOpcode()); - assertEquals("Fin must be set", true, binary.isFin()); - assertEquals("TransferedMask must not be set", false, binary.getTransfereMasked()); - assertEquals("Payload must be empty", 0, binary.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, binary.isRSV1()); - assertEquals("RSV2 must be false", false, binary.isRSV2()); - assertEquals("RSV3 must be false", false, binary.isRSV3()); + assertEquals(Opcode.BINARY, binary.getOpcode(), "Opcode must be equal"); + assertTrue(binary.isFin(), "Fin must be set"); + assertFalse(binary.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, binary.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(binary.isRSV1(), "RSV1 must be false"); + assertFalse(binary.isRSV2(), "RSV2 must be false"); + assertFalse(binary.isRSV3(), "RSV3 must be false"); } @Test public void testGet() { FramedataImpl1 binary = FramedataImpl1.get(Opcode.BINARY); - assertEquals("Frame must be binary", true, binary instanceof BinaryFrame); + assertInstanceOf(BinaryFrame.class, binary, "Frame must be binary"); FramedataImpl1 text = FramedataImpl1.get(Opcode.TEXT); - assertEquals("Frame must be text", true, text instanceof TextFrame); + assertInstanceOf(TextFrame.class, text, "Frame must be text"); FramedataImpl1 closing = FramedataImpl1.get(Opcode.CLOSING); - assertEquals("Frame must be closing", true, closing instanceof CloseFrame); + assertInstanceOf(CloseFrame.class, closing, "Frame must be closing"); FramedataImpl1 continuous = FramedataImpl1.get(Opcode.CONTINUOUS); - assertEquals("Frame must be continuous", true, continuous instanceof ContinuousFrame); + assertInstanceOf(ContinuousFrame.class, continuous, "Frame must be continuous"); FramedataImpl1 ping = FramedataImpl1.get(Opcode.PING); - assertEquals("Frame must be ping", true, ping instanceof PingFrame); + assertInstanceOf(PingFrame.class, ping, "Frame must be ping"); FramedataImpl1 pong = FramedataImpl1.get(Opcode.PONG); - assertEquals("Frame must be pong", true, pong instanceof PongFrame); + assertInstanceOf(PongFrame.class, pong, "Frame must be pong"); try { FramedataImpl1.get(null); fail("IllegalArgumentException should be thrown"); @@ -76,18 +75,18 @@ public void testGet() { public void testSetters() { FramedataImpl1 frame = FramedataImpl1.get(Opcode.BINARY); frame.setFin(false); - assertEquals("Fin must not be set", false, frame.isFin()); + assertFalse(frame.isFin(), "Fin must not be set"); frame.setTransferemasked(true); - assertEquals("TransferedMask must be set", true, frame.getTransfereMasked()); + assertTrue(frame.getTransfereMasked(), "TransferedMask must be set"); ByteBuffer buffer = ByteBuffer.allocate(100); frame.setPayload(buffer); - assertEquals("Payload must be of size 100", 100, frame.getPayloadData().capacity()); + assertEquals( 100, frame.getPayloadData().capacity(), "Payload must be of size 100"); frame.setRSV1(true); - assertEquals("RSV1 must be true", true, frame.isRSV1()); + assertTrue(frame.isRSV1(), "RSV1 must be true"); frame.setRSV2(true); - assertEquals("RSV2 must be true", true, frame.isRSV2()); + assertTrue(frame.isRSV2(), "RSV2 must be true"); frame.setRSV3(true); - assertEquals("RSV3 must be true", true, frame.isRSV3()); + assertTrue(frame.isRSV3(), "RSV3 must be true"); } @Test @@ -98,8 +97,8 @@ public void testAppend() { FramedataImpl1 frame1 = FramedataImpl1.get(Opcode.BINARY); frame1.setPayload(ByteBuffer.wrap("second".getBytes())); frame0.append(frame1); - assertEquals("Fin must be set", true, frame0.isFin()); - assertArrayEquals("Payload must be equal", "firstsecond".getBytes(), - frame0.getPayloadData().array()); + assertTrue(frame0.isFin(), "Fin must be set"); + assertArrayEquals( "firstsecond".getBytes(), + frame0.getPayloadData().array(), "Payload must be equal"); } } diff --git a/src/test/java/org/java_websocket/framing/PingFrameTest.java b/src/test/java/org/java_websocket/framing/PingFrameTest.java index e5c90d4dd..9ccdc7580 100644 --- a/src/test/java/org/java_websocket/framing/PingFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PingFrameTest.java @@ -25,79 +25,78 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the PingFrame class */ public class PingFrameTest { - @Test - public void testConstructor() { - PingFrame frame = new PingFrame(); - assertEquals("Opcode must be equal", Opcode.PING, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); + @Test + public void testConstructor() { + PingFrame frame = new PingFrame(); + assertEquals(Opcode.PING, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals(0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } } - } - @Test - public void testExtends() { - PingFrame frame = new PingFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); - } - - @Test - public void testIsValid() { - PingFrame frame = new PingFrame(); - try { - frame.isValid(); - } catch (InvalidDataException e) { - fail("InvalidDataException should not be thrown"); - } - frame.setFin(false); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine + @Test + public void testExtends() { + PingFrame frame = new PingFrame(); + assertInstanceOf(ControlFrame.class, frame, "Frame must extend dataframe"); } - frame.setFin(true); - frame.setRSV1(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV1(false); - frame.setRSV2(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine - } - frame.setRSV2(false); - frame.setRSV3(true); - try { - frame.isValid(); - fail("InvalidDataException should be thrown"); - } catch (InvalidDataException e) { - //Fine + + @Test + public void testIsValid() { + PingFrame frame = new PingFrame(); + try { + frame.isValid(); + } catch (InvalidDataException e) { + fail("InvalidDataException should not be thrown"); + } + frame.setFin(false); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setFin(true); + frame.setRSV1(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV1(false); + frame.setRSV2(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } + frame.setRSV2(false); + frame.setRSV3(true); + try { + frame.isValid(); + fail("InvalidDataException should be thrown"); + } catch (InvalidDataException e) { + //Fine + } } - } } diff --git a/src/test/java/org/java_websocket/framing/PongFrameTest.java b/src/test/java/org/java_websocket/framing/PongFrameTest.java index c98c09ccc..d2985b7a9 100644 --- a/src/test/java/org/java_websocket/framing/PongFrameTest.java +++ b/src/test/java/org/java_websocket/framing/PongFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the PongFrame class @@ -41,13 +41,13 @@ public class PongFrameTest { @Test public void testConstructor() { PongFrame frame = new PongFrame(); - assertEquals("Opcode must be equal", Opcode.PONG, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.PONG, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, frame.getPayloadData().capacity(),"Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -60,13 +60,13 @@ public void testCopyConstructor() { PingFrame pingFrame = new PingFrame(); pingFrame.setPayload(ByteBuffer.allocate(100)); PongFrame pongFrame = new PongFrame(pingFrame); - assertEquals("Payload must be equal", pingFrame.getPayloadData(), pongFrame.getPayloadData()); + assertEquals( pingFrame.getPayloadData(), pongFrame.getPayloadData(), "Payload must be equal"); } @Test public void testExtends() { PongFrame frame = new PongFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof ControlFrame); + assertInstanceOf(ControlFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/framing/TextFrameTest.java b/src/test/java/org/java_websocket/framing/TextFrameTest.java index d4e0dabc6..21f83f1c9 100644 --- a/src/test/java/org/java_websocket/framing/TextFrameTest.java +++ b/src/test/java/org/java_websocket/framing/TextFrameTest.java @@ -25,13 +25,13 @@ package org.java_websocket.framing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.nio.ByteBuffer; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the TextFrame class @@ -41,13 +41,13 @@ public class TextFrameTest { @Test public void testConstructor() { TextFrame frame = new TextFrame(); - assertEquals("Opcode must be equal", Opcode.TEXT, frame.getOpcode()); - assertEquals("Fin must be set", true, frame.isFin()); - assertEquals("TransferedMask must not be set", false, frame.getTransfereMasked()); - assertEquals("Payload must be empty", 0, frame.getPayloadData().capacity()); - assertEquals("RSV1 must be false", false, frame.isRSV1()); - assertEquals("RSV2 must be false", false, frame.isRSV2()); - assertEquals("RSV3 must be false", false, frame.isRSV3()); + assertEquals(Opcode.TEXT, frame.getOpcode(), "Opcode must be equal"); + assertTrue(frame.isFin(), "Fin must be set"); + assertFalse(frame.getTransfereMasked(), "TransferedMask must not be set"); + assertEquals( 0, frame.getPayloadData().capacity(), "Payload must be empty"); + assertFalse(frame.isRSV1(), "RSV1 must be false"); + assertFalse(frame.isRSV2(), "RSV2 must be false"); + assertFalse(frame.isRSV3(), "RSV3 must be false"); try { frame.isValid(); } catch (InvalidDataException e) { @@ -58,7 +58,7 @@ public void testConstructor() { @Test public void testExtends() { TextFrame frame = new TextFrame(); - assertEquals("Frame must extend dataframe", true, frame instanceof DataFrame); + assertInstanceOf(DataFrame.class, frame, "Frame must extend dataframe"); } @Test diff --git a/src/test/java/org/java_websocket/issues/AllIssueTests.java b/src/test/java/org/java_websocket/issues/AllIssueTests.java deleted file mode 100644 index 3668bcb89..000000000 --- a/src/test/java/org/java_websocket/issues/AllIssueTests.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.issues; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.issues.Issue609Test.class, - org.java_websocket.issues.Issue621Test.class, - org.java_websocket.issues.Issue580Test.class, - org.java_websocket.issues.Issue598Test.class, - org.java_websocket.issues.Issue256Test.class, - org.java_websocket.issues.Issue661Test.class, - org.java_websocket.issues.Issue666Test.class, - org.java_websocket.issues.Issue677Test.class, - org.java_websocket.issues.Issue732Test.class, - org.java_websocket.issues.Issue764Test.class, - org.java_websocket.issues.Issue765Test.class, - org.java_websocket.issues.Issue825Test.class, - org.java_websocket.issues.Issue834Test.class, - org.java_websocket.issues.Issue962Test.class -}) -/** - * Start all tests for issues - */ -public class AllIssueTests { - -} diff --git a/src/test/java/org/java_websocket/issues/Issue1142Test.java b/src/test/java/org/java_websocket/issues/Issue1142Test.java index 21de76bb6..38ff93e4d 100644 --- a/src/test/java/org/java_websocket/issues/Issue1142Test.java +++ b/src/test/java/org/java_websocket/issues/Issue1142Test.java @@ -1,9 +1,5 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -23,13 +19,17 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class Issue1142Test { - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithoutSSLSession() throws IOException, URISyntaxException, InterruptedException { int port = SocketUtil.getAvailablePort(); @@ -66,7 +66,8 @@ public void onError(Exception ex) { server.stop(); } - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); diff --git a/src/test/java/org/java_websocket/issues/Issue1160Test.java b/src/test/java/org/java_websocket/issues/Issue1160Test.java index e456132cc..57983cdea 100644 --- a/src/test/java/org/java_websocket/issues/Issue1160Test.java +++ b/src/test/java/org/java_websocket/issues/Issue1160Test.java @@ -6,8 +6,8 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.net.InetSocketAddress; import java.net.URI; @@ -15,6 +15,9 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + public class Issue1160Test { private final CountDownLatch countServerStart = new CountDownLatch(1); @@ -45,7 +48,8 @@ public void onError(Exception ex) { } - @Test(timeout = 5000) + @Test + @Timeout(5000) public void nonFatalErrorShallBeHandledByServer() throws Exception { final AtomicInteger isServerOnErrorCalledCounter = new AtomicInteger(0); @@ -99,12 +103,13 @@ public void onStart() { client.closeBlocking(); } - Assert.assertEquals(CONNECTION_COUNT, isServerOnErrorCalledCounter.get()); + assertEquals(CONNECTION_COUNT, isServerOnErrorCalledCounter.get()); server.stop(); } - @Test(timeout = 5000) + @Test + @Timeout(5000) public void fatalErrorShallNotBeHandledByServer() throws Exception { int port = SocketUtil.getAvailablePort(); @@ -121,7 +126,7 @@ public void onClose(WebSocket conn, int code, String reason, boolean remote) { @Override public void onMessage(WebSocket conn, ByteBuffer message) { - throw new OutOfMemoryError("Some error"); + throw new OutOfMemoryError("Some intentional error"); } @Override @@ -154,6 +159,7 @@ public void onStart() { client.send(new byte[100]); countClientDownLatch.await(); countServerDownLatch.await(); - Assert.assertTrue(countClientDownLatch.getCount() == 0 && countServerDownLatch.getCount() == 0); + assertEquals(0,countClientDownLatch.getCount()); + assertEquals(0, countServerDownLatch.getCount()); } } diff --git a/src/test/java/org/java_websocket/issues/Issue1203Test.java b/src/test/java/org/java_websocket/issues/Issue1203Test.java index 32ef85235..45c4cd593 100644 --- a/src/test/java/org/java_websocket/issues/Issue1203Test.java +++ b/src/test/java/org/java_websocket/issues/Issue1203Test.java @@ -1,8 +1,5 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.net.InetSocketAddress; import java.net.URI; @@ -15,14 +12,18 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertFalse; + public class Issue1203Test { private final CountDownLatch countServerDownLatch = new CountDownLatch(1); private final CountDownLatch countClientDownLatch = new CountDownLatch(1); boolean isClosedCalled = false; - @Test(timeout = 50000) + @Test + @Timeout(50000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { @@ -88,7 +89,7 @@ public void run() { timer.schedule(task, 15000); countClientDownLatch.await(); Thread.sleep(30000); - Assert.assertFalse(isClosedCalled); + assertFalse(isClosedCalled); client.closeBlocking(); server.stop(); } diff --git a/src/test/java/org/java_websocket/issues/Issue256Test.java b/src/test/java/org/java_websocket/issues/Issue256Test.java index 4faf1fa14..30d461459 100644 --- a/src/test/java/org/java_websocket/issues/Issue256Test.java +++ b/src/test/java/org/java_websocket/issues/Issue256Test.java @@ -25,9 +25,6 @@ package org.java_websocket.issues; -import static org.hamcrest.core.Is.is; -import static org.junit.Assume.assumeThat; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -42,14 +39,16 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(ThreadCheck.class) public class Issue256Test { private static final int NUMBER_OF_TESTS = 10; @@ -57,13 +56,8 @@ public class Issue256Test { private static int port; static CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Rule - public ThreadCheck zombies = new ThreadCheck(); - @Parameterized.Parameter - public int count; - - @BeforeClass + @BeforeAll public static void startServer() throws Exception { port = SocketUtil.getAvailablePort(); ws = new WebSocketServer(new InetSocketAddress(port), 16) { @@ -84,10 +78,7 @@ public void onMessage(WebSocket conn, String message) { @Override public void onError(WebSocket conn, Exception ex) { - - ex.printStackTrace(); - assumeThat(true, is(false)); - System.out.println("There should be no exception!"); + fail("There should be no exception!"); } @Override @@ -121,9 +112,7 @@ public void onClose(int code, String reason, boolean remote) { @Override public void onError(Exception ex) { - ex.printStackTrace(); - assumeThat(true, is(false)); - System.out.println("There should be no exception!"); + fail("There should be no exception!"); } }; clt.connectBlocking(); @@ -137,12 +126,11 @@ public void onError(Exception ex) { clt.closeBlocking(); } - @AfterClass + @AfterAll public static void successTests() throws InterruptedException, IOException { ws.stop(); } - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 0; i < NUMBER_OF_TESTS; i++) { @@ -151,12 +139,16 @@ public static Collection data() { return ret; } - @Test(timeout = 5000) + @ParameterizedTest + @Timeout(5000) + @MethodSource("data") public void runReconnectSocketClose() throws Exception { runTestScenarioReconnect(false); } - @Test(timeout = 5000) + @ParameterizedTest + @Timeout(5000) + @MethodSource("data") public void runReconnectCloseBlocking() throws Exception { runTestScenarioReconnect(true); } diff --git a/src/test/java/org/java_websocket/issues/Issue580Test.java b/src/test/java/org/java_websocket/issues/Issue580Test.java index 4a2e31848..e50e5f839 100644 --- a/src/test/java/org/java_websocket/issues/Issue580Test.java +++ b/src/test/java/org/java_websocket/issues/Issue580Test.java @@ -38,22 +38,15 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) +@ExtendWith(ThreadCheck.class) public class Issue580Test { private static final int NUMBER_OF_TESTS = 10; - @Parameterized.Parameter - public int count; - - - @Rule - public ThreadCheck zombies = new ThreadCheck(); private void runTestScenario(boolean closeBlocking) throws Exception { final CountDownLatch countServerDownLatch = new CountDownLatch(1); @@ -116,7 +109,6 @@ public void onError(Exception ex) { Thread.sleep(100); } - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 0; i < NUMBER_OF_TESTS; i++) { @@ -125,12 +117,15 @@ public static Collection data() { return ret; } - @Test + + @ParameterizedTest + @MethodSource("data") public void runNoCloseBlockingTestScenario() throws Exception { runTestScenario(false); } - @Test + @ParameterizedTest + @MethodSource("data") public void runCloseBlockingTestScenario() throws Exception { runTestScenario(true); } diff --git a/src/test/java/org/java_websocket/issues/Issue598Test.java b/src/test/java/org/java_websocket/issues/Issue598Test.java index c45f228cb..26c12f56a 100644 --- a/src/test/java/org/java_websocket/issues/Issue598Test.java +++ b/src/test/java/org/java_websocket/issues/Issue598Test.java @@ -44,7 +44,8 @@ import org.java_websocket.protocols.Protocol; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue598Test { @@ -189,43 +190,50 @@ public void onStart() { server.stop(); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowLimitBytebuffer() throws Exception { runTestScenario(0); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowSplitLimitBytebuffer() throws Exception { runTestScenario(1); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowLimitString() throws Exception { runTestScenario(2); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runBelowSplitLimitString() throws Exception { runTestScenario(3); } @Test - //(timeout = 2000) + @Timeout(2000) public void runAboveLimitBytebuffer() throws Exception { runTestScenario(4); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runAboveSplitLimitBytebuffer() throws Exception { runTestScenario(5); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runAboveLimitString() throws Exception { runTestScenario(6); } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void runAboveSplitLimitString() throws Exception { runTestScenario(7); } diff --git a/src/test/java/org/java_websocket/issues/Issue609Test.java b/src/test/java/org/java_websocket/issues/Issue609Test.java index b84e3cfd9..4c89b784a 100644 --- a/src/test/java/org/java_websocket/issues/Issue609Test.java +++ b/src/test/java/org/java_websocket/issues/Issue609Test.java @@ -25,8 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertTrue; - import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.CountDownLatch; @@ -36,7 +34,10 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue609Test { @@ -99,12 +100,12 @@ public void onStart() { server.start(); countServerDownLatch.await(); webSocket.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket.isOpen()); + assertTrue(webSocket.isOpen(), "webSocket.isOpen()"); webSocket.getSocket().close(); countDownLatch.await(); - assertTrue("!webSocket.isOpen()", !webSocket.isOpen()); - assertTrue("!wasOpenClient", !wasOpenClient); - assertTrue("!wasOpenServer", !wasOpenServer); + assertFalse(webSocket.isOpen(), "!webSocket.isOpen()"); + assertFalse(wasOpenClient, "!wasOpenClient"); + assertFalse(wasOpenServer, "!wasOpenServer"); server.stop(); } } diff --git a/src/test/java/org/java_websocket/issues/Issue621Test.java b/src/test/java/org/java_websocket/issues/Issue621Test.java index 1a6a173ad..f21c40071 100644 --- a/src/test/java/org/java_websocket/issues/Issue621Test.java +++ b/src/test/java/org/java_websocket/issues/Issue621Test.java @@ -25,8 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertTrue; - import java.io.OutputStream; import java.io.PrintStream; import java.net.InetSocketAddress; @@ -38,7 +36,9 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; public class Issue621Test { @@ -114,7 +114,7 @@ public void onStart() { countServerDownLatch.await(); webSocket.connectBlocking(); countDownLatch.await(); - assertTrue("There was an error using System.err", !wasError); + assertFalse(wasError, "There was an error using System.err"); server.stop(); } } diff --git a/src/test/java/org/java_websocket/issues/Issue661Test.java b/src/test/java/org/java_websocket/issues/Issue661Test.java index bda984431..31cded8fc 100644 --- a/src/test/java/org/java_websocket/issues/Issue661Test.java +++ b/src/test/java/org/java_websocket/issues/Issue661Test.java @@ -25,9 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.net.BindException; import java.net.InetSocketAddress; @@ -37,20 +34,22 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; -public class Issue661Test { +import static org.junit.jupiter.api.Assertions.*; - @Rule - public ThreadCheck zombies = new ThreadCheck(); +@ExtendWith(ThreadCheck.class) +public class Issue661Test { private CountDownLatch countServerDownLatch = new CountDownLatch(1); private boolean wasError = false; private boolean wasBindException = false; - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); WebSocketServer server0 = new WebSocketServer(new InetSocketAddress(port)) { @@ -120,7 +119,7 @@ public void onStart() { server1.stop(); server0.stop(); Thread.sleep(100); - assertFalse("There was an unexpected exception!", wasError); - assertTrue("There was no bind exception!", wasBindException); + assertFalse(wasError, "There was an unexpected exception!"); + assertTrue(wasBindException, "There was no bind exception!"); } } diff --git a/src/test/java/org/java_websocket/issues/Issue666Test.java b/src/test/java/org/java_websocket/issues/Issue666Test.java index a4f2523b5..163dd2366 100644 --- a/src/test/java/org/java_websocket/issues/Issue666Test.java +++ b/src/test/java/org/java_websocket/issues/Issue666Test.java @@ -29,6 +29,7 @@ import java.net.URI; import java.util.Map; import java.util.concurrent.CountDownLatch; + import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -36,122 +37,127 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Assert; -import org.junit.Test; - -public class Issue666Test { - - private CountDownLatch countServerDownLatch = new CountDownLatch(1); - - @Test - public void testServer() throws Exception { - Map mapBefore = ThreadCheck.getThreadMap(); - int port = SocketUtil.getAvailablePort(); - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - - } +import org.junit.jupiter.api.Test; - @Override - public void onMessage(WebSocket conn, String message) { +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } +public class Issue666Test { - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - Map mapAfter = ThreadCheck.getThreadMap(); - for (long key : mapBefore.keySet()) { - mapAfter.remove(key); + private CountDownLatch countServerDownLatch = new CountDownLatch(1); + + @Test + public void testServer() throws Exception { + Map mapBefore = ThreadCheck.getThreadMap(); + int port = SocketUtil.getAvailablePort(); + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + Map mapAfter = ThreadCheck.getThreadMap(); + for (long key : mapBefore.keySet()) { + mapAfter.remove(key); + } + for (Thread thread : mapAfter.values()) { + String name = thread.getName(); + if (!name.startsWith("WebSocketSelector-") && !name.startsWith("WebSocketWorker-") && !name + .startsWith("WebSocketConnectionLostChecker-") + && !name.startsWith("WebSocketConnectReadThread-")) { + fail("Thread not correctly named! Is: " + name); + } + } + server.stop(); } - for (Thread thread : mapAfter.values()) { - String name = thread.getName(); - if (!name.startsWith("WebSocketSelector-") && !name.startsWith("WebSocketWorker-") && !name - .startsWith("connectionLostChecker-")) { - Assert.fail("Thread not correctly named! Is: " + name); - } - } - server.stop(); - } - - @Test - public void testClient() throws Exception { - int port = SocketUtil.getAvailablePort(); - WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - - } - @Override - public void onMessage(String message) { - - } - - @Override - public void onClose(int code, String reason, boolean remote) { - } - - @Override - public void onError(Exception ex) { - - } - }; - WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } - - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - - } - - @Override - public void onMessage(WebSocket conn, String message) { - - } - - @Override - public void onError(WebSocket conn, Exception ex) { - - } - - @Override - public void onStart() { - countServerDownLatch.countDown(); - } - }; - server.start(); - countServerDownLatch.await(); - Map mapBefore = ThreadCheck.getThreadMap(); - client.connectBlocking(); - Map mapAfter = ThreadCheck.getThreadMap(); - for (long key : mapBefore.keySet()) { - mapAfter.remove(key); - } - for (Thread thread : mapAfter.values()) { - String name = thread.getName(); - if (!name.startsWith("connectionLostChecker-") && !name.startsWith("WebSocketWriteThread-") - && !name.startsWith("WebSocketConnectReadThread-")) { - Assert.fail("Thread not correctly named! Is: " + name); - } + @Test + public void testClient() throws Exception { + int port = SocketUtil.getAvailablePort(); + WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + + } + + @Override + public void onMessage(String message) { + + } + + @Override + public void onClose(int code, String reason, boolean remote) { + } + + @Override + public void onError(Exception ex) { + + } + }; + WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } + }; + server.start(); + countServerDownLatch.await(); + assertTrue(SocketUtil.waitForServerToStart(port), "Server Start Status"); + Map mapBefore = ThreadCheck.getThreadMap(); + client.connectBlocking(); + Map mapAfter = ThreadCheck.getThreadMap(); + for (long key : mapBefore.keySet()) { + mapAfter.remove(key); + } + for (Thread thread : mapAfter.values()) { + String name = thread.getName(); + if (!name.startsWith("WebSocketConnectionLostChecker-") && !name.startsWith("WebSocketWriteThread-") + && !name.startsWith("WebSocketConnectReadThread-") + && !name.startsWith("WebSocketWorker-")) { + fail("Thread not correctly named! Is: " + name); + } + } + client.close(); + server.stop(); } - client.close(); - server.stop(); - } } diff --git a/src/test/java/org/java_websocket/issues/Issue677Test.java b/src/test/java/org/java_websocket/issues/Issue677Test.java index 52dfc94b7..bf660d789 100644 --- a/src/test/java/org/java_websocket/issues/Issue677Test.java +++ b/src/test/java/org/java_websocket/issues/Issue677Test.java @@ -25,7 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertTrue; import java.net.InetSocketAddress; import java.net.URI; @@ -37,7 +36,9 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue677Test { @@ -113,14 +114,21 @@ public void onStart() { server.start(); countServerDownLatch.await(); webSocket0.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket0.isOpen()); + assertTrue(webSocket0.isOpen(), "webSocket.isOpen()"); webSocket0.close(); countDownLatch0.await(); - assertTrue("webSocket.isClosed()", webSocket0.isClosed()); + // Add some delay is since the latch will be decreased in the onClose before the state is reset + for (int i = 0; i < 5; i++) { + if (webSocket0.isClosed()) { + break; + } + Thread.sleep(5); + } + assertTrue(webSocket0.isClosed(), "webSocket.isClosed()"); webSocket1.connectBlocking(); - assertTrue("webSocket.isOpen()", webSocket1.isOpen()); + assertTrue(webSocket1.isOpen(), "webSocket.isOpen()"); webSocket1.closeConnection(CloseFrame.ABNORMAL_CLOSE, "Abnormal close!"); - assertTrue("webSocket.isClosed()", webSocket1.isClosed()); + assertTrue(webSocket1.isClosed(), "webSocket.isClosed()"); server.stop(); } } diff --git a/src/test/java/org/java_websocket/issues/Issue713Test.java b/src/test/java/org/java_websocket/issues/Issue713Test.java index 1b752aaf8..769f08f94 100644 --- a/src/test/java/org/java_websocket/issues/Issue713Test.java +++ b/src/test/java/org/java_websocket/issues/Issue713Test.java @@ -25,8 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -40,7 +38,10 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.fail; public class Issue713Test { @@ -49,7 +50,7 @@ public class Issue713Test { CountDownLatch countDownLatchBytebuffer = new CountDownLatch(10); @Test - public void testIllegalArgument() throws IOException { + public void testIllegalArgument() throws InterruptedException { WebSocketServer server = new WebSocketServer( new InetSocketAddress(SocketUtil.getAvailablePort())) { @Override @@ -91,7 +92,8 @@ public void onStart() { } } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { final int port = SocketUtil.getAvailablePort(); WebSocketServer server = new WebSocketServer(new InetSocketAddress(port)) { diff --git a/src/test/java/org/java_websocket/issues/Issue732Test.java b/src/test/java/org/java_websocket/issues/Issue732Test.java index e811f8aa0..d9e734bbe 100644 --- a/src/test/java/org/java_websocket/issues/Issue732Test.java +++ b/src/test/java/org/java_websocket/issues/Issue732Test.java @@ -25,7 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.fail; import java.net.InetSocketAddress; import java.net.URI; @@ -37,18 +36,20 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; import org.java_websocket.util.ThreadCheck; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import static org.junit.jupiter.api.Assertions.fail; + +@ExtendWith(ThreadCheck.class) public class Issue732Test { - @Rule - public ThreadCheck zombies = new ThreadCheck(); private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); final WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { @@ -56,7 +57,7 @@ public void testIssue() throws Exception { public void onOpen(ServerHandshake handshakedata) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { // } @@ -66,7 +67,7 @@ public void onOpen(ServerHandshake handshakedata) { public void onMessage(String message) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { send("hi"); } @@ -76,7 +77,7 @@ public void onMessage(String message) { public void onClose(int code, String reason, boolean remote) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { // } @@ -86,7 +87,7 @@ public void onClose(int code, String reason, boolean remote) { public void onError(Exception ex) { try { this.reconnect(); - Assert.fail("Exception should be thrown"); + fail("Exception should be thrown"); } catch (IllegalStateException e) { // } diff --git a/src/test/java/org/java_websocket/issues/Issue764Test.java b/src/test/java/org/java_websocket/issues/Issue764Test.java index 40be7ef6c..870f79ad9 100644 --- a/src/test/java/org/java_websocket/issues/Issue764Test.java +++ b/src/test/java/org/java_websocket/issues/Issue764Test.java @@ -45,14 +45,16 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue764Test { private CountDownLatch countClientDownLatch = new CountDownLatch(2); private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); diff --git a/src/test/java/org/java_websocket/issues/Issue765Test.java b/src/test/java/org/java_websocket/issues/Issue765Test.java index a7a6188cd..5eff49468 100644 --- a/src/test/java/org/java_websocket/issues/Issue765Test.java +++ b/src/test/java/org/java_websocket/issues/Issue765Test.java @@ -38,8 +38,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue765Test { @@ -49,9 +51,9 @@ public class Issue765Test { public void testIssue() { WebSocketServer webSocketServer = new MyWebSocketServer(); webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); - Assert.assertFalse("Close should not have been called yet", isClosedCalled); + assertFalse(isClosedCalled, "Close should not have been called yet"); webSocketServer.setWebSocketFactory(new LocalWebSocketFactory()); - Assert.assertTrue("Close has been called", isClosedCalled); + assertTrue(isClosedCalled, "Close has been called"); } private static class MyWebSocketServer extends WebSocketServer { diff --git a/src/test/java/org/java_websocket/issues/Issue811Test.java b/src/test/java/org/java_websocket/issues/Issue811Test.java index d438aa685..e2faf7ed2 100644 --- a/src/test/java/org/java_websocket/issues/Issue811Test.java +++ b/src/test/java/org/java_websocket/issues/Issue811Test.java @@ -33,13 +33,15 @@ import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue811Test { private CountDownLatch countServerDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testSetConnectionLostTimeout() throws IOException, InterruptedException { final MyWebSocketServer server = new MyWebSocketServer( new InetSocketAddress(SocketUtil.getAvailablePort())); diff --git a/src/test/java/org/java_websocket/issues/Issue825Test.java b/src/test/java/org/java_websocket/issues/Issue825Test.java index d878dddde..f846f9571 100644 --- a/src/test/java/org/java_websocket/issues/Issue825Test.java +++ b/src/test/java/org/java_websocket/issues/Issue825Test.java @@ -45,12 +45,14 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue825Test { - @Test(timeout = 15000) + @Test + @Timeout(15000) public void testIssue() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { final CountDownLatch countClientOpenLatch = new CountDownLatch(3); diff --git a/src/test/java/org/java_websocket/issues/Issue834Test.java b/src/test/java/org/java_websocket/issues/Issue834Test.java index 350acf456..abd121179 100644 --- a/src/test/java/org/java_websocket/issues/Issue834Test.java +++ b/src/test/java/org/java_websocket/issues/Issue834Test.java @@ -7,13 +7,17 @@ import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertEquals; + public class Issue834Test { - @Test(timeout = 1000) - public void testNoNewThreads() throws IOException { + @Test + @Timeout(1000) + public void testNoNewThreads() throws InterruptedException { Set threadSet1 = Thread.getAllStackTraces().keySet(); @@ -42,7 +46,7 @@ public void onStart() { Set threadSet2 = Thread.getAllStackTraces().keySet(); //checks that no threads are started in the constructor - Assert.assertEquals(threadSet1, threadSet2); + assertEquals(threadSet1, threadSet2); } diff --git a/src/test/java/org/java_websocket/issues/Issue847Test.java b/src/test/java/org/java_websocket/issues/Issue847Test.java index f47e4fec5..870e18b07 100644 --- a/src/test/java/org/java_websocket/issues/Issue847Test.java +++ b/src/test/java/org/java_websocket/issues/Issue847Test.java @@ -26,8 +26,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; @@ -45,13 +43,14 @@ import org.java_websocket.util.Charsetfunctions; import org.java_websocket.util.KeyUtils; import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; -@RunWith(Parameterized.class) public class Issue847Test { private static Thread thread; @@ -60,10 +59,6 @@ public class Issue847Test { private static int port; private static final int NUMBER_OF_TESTS = 20; - @Parameterized.Parameter - public int size; - - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 1; i <= NUMBER_OF_TESTS + 1; i++) { @@ -72,7 +67,7 @@ public static Collection data() { return ret; } - @BeforeClass + @BeforeAll public static void startServer() throws Exception { port = SocketUtil.getAvailablePort(); thread = new Thread( @@ -138,19 +133,23 @@ public void run() { thread.start(); } - @AfterClass + @AfterAll public static void successTests() throws IOException { serverSocket.close(); thread.interrupt(); } - @Test(timeout = 5000) - public void testIncrementalFrameUnmasked() throws Exception { + @ParameterizedTest() + @Timeout(5000) + @MethodSource("data") + public void testIncrementalFrameUnmasked(int size) throws Exception { testIncrementalFrame(false, size); } - @Test(timeout = 5000) - public void testIncrementalFrameMsked() throws Exception { + @ParameterizedTest() + @Timeout(5000) + @MethodSource("data") + public void testIncrementalFrameMsked(int size) throws Exception { testIncrementalFrame(true, size); } diff --git a/src/test/java/org/java_websocket/issues/Issue855Test.java b/src/test/java/org/java_websocket/issues/Issue855Test.java index 9f919b87e..f094f067e 100644 --- a/src/test/java/org/java_websocket/issues/Issue855Test.java +++ b/src/test/java/org/java_websocket/issues/Issue855Test.java @@ -35,14 +35,16 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue855Test { CountDownLatch countServerDownLatch = new CountDownLatch(1); CountDownLatch countDownLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); WebSocketClient webSocket = new WebSocketClient(new URI("ws://localhost:" + port)) { diff --git a/src/test/java/org/java_websocket/issues/Issue879Test.java b/src/test/java/org/java_websocket/issues/Issue879Test.java index bdd6fa1c0..504bec922 100644 --- a/src/test/java/org/java_websocket/issues/Issue879Test.java +++ b/src/test/java/org/java_websocket/issues/Issue879Test.java @@ -26,8 +26,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; - import java.io.IOException; import java.net.BindException; import java.net.InetSocketAddress; @@ -45,21 +43,21 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertFalse; -@RunWith(Parameterized.class) public class Issue879Test { private static final int NUMBER_OF_TESTS = 20; - @Parameterized.Parameter - public int numberOfConnections; - - - @Test(timeout = 10000) - public void QuickStopTest() throws IOException, InterruptedException, URISyntaxException { + @Timeout(10000) + @ParameterizedTest() + @MethodSource("data") + public void QuickStopTest(int numberOfConnections) throws InterruptedException, URISyntaxException { final boolean[] wasBindException = {false}; final boolean[] wasConcurrentException = new boolean[1]; final CountDownLatch countDownLatch = new CountDownLatch(1); @@ -122,11 +120,10 @@ public void onStart() { serverA.stop(); serverB.start(); clients.clear(); - assertFalse("There was a BindException", wasBindException[0]); - assertFalse("There was a ConcurrentModificationException", wasConcurrentException[0]); + assertFalse(wasBindException[0], "There was a BindException"); + assertFalse(wasConcurrentException[0], "There was a ConcurrentModificationException"); } - @Parameterized.Parameters public static Collection data() { List ret = new ArrayList(NUMBER_OF_TESTS); for (int i = 0; i < NUMBER_OF_TESTS; i++) { diff --git a/src/test/java/org/java_websocket/issues/Issue890Test.java b/src/test/java/org/java_websocket/issues/Issue890Test.java index 7f05a23a4..82c991bab 100644 --- a/src/test/java/org/java_websocket/issues/Issue890Test.java +++ b/src/test/java/org/java_websocket/issues/Issue890Test.java @@ -26,10 +26,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.InetSocketAddress; @@ -51,12 +47,16 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class Issue890Test { - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); @@ -92,7 +92,8 @@ public void onError(Exception ex) { assertNotNull(testResult.sslSession); } - @Test(timeout = 4000) + @Test + @Timeout(4000) public void testWithOutSSLSession() throws IOException, URISyntaxException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, InterruptedException { int port = SocketUtil.getAvailablePort(); diff --git a/src/test/java/org/java_websocket/issues/Issue900Test.java b/src/test/java/org/java_websocket/issues/Issue900Test.java index 952dca8ee..edc966e9f 100644 --- a/src/test/java/org/java_websocket/issues/Issue900Test.java +++ b/src/test/java/org/java_websocket/issues/Issue900Test.java @@ -40,14 +40,16 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class Issue900Test { CountDownLatch serverStartLatch = new CountDownLatch(1); CountDownLatch closeCalledLatch = new CountDownLatch(1); - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws Exception { int port = SocketUtil.getAvailablePort(); final WebSocketClient client = new WebSocketClient(new URI("ws://localhost:" + port)) { diff --git a/src/test/java/org/java_websocket/issues/Issue941Test.java b/src/test/java/org/java_websocket/issues/Issue941Test.java index a9aedbaef..eaf50fab3 100644 --- a/src/test/java/org/java_websocket/issues/Issue941Test.java +++ b/src/test/java/org/java_websocket/issues/Issue941Test.java @@ -25,7 +25,6 @@ package org.java_websocket.issues; -import static org.junit.Assert.assertArrayEquals; import java.net.InetSocketAddress; import java.net.URI; @@ -39,7 +38,9 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; public class Issue941Test { diff --git a/src/test/java/org/java_websocket/issues/Issue962Test.java b/src/test/java/org/java_websocket/issues/Issue962Test.java index b7d107171..56baa6d34 100644 --- a/src/test/java/org/java_websocket/issues/Issue962Test.java +++ b/src/test/java/org/java_websocket/issues/Issue962Test.java @@ -31,6 +31,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; +import java.util.concurrent.CountDownLatch; import javax.net.SocketFactory; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; @@ -38,8 +39,10 @@ import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.*; public class Issue962Test { @@ -86,7 +89,8 @@ public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throw } - @Test(timeout = 2000) + @Test + @Timeout(2000) public void testIssue() throws IOException, URISyntaxException, InterruptedException { int port = SocketUtil.getAvailablePort(); WebSocketClient client = new WebSocketClient(new URI("ws://127.0.0.1:" + port)) { @@ -104,11 +108,12 @@ public void onClose(int code, String reason, boolean remote) { @Override public void onError(Exception ex) { - Assert.fail(ex.toString() + " should not occur"); + fail(ex.toString() + " should not occur"); } }; String bindingAddress = "127.0.0.1"; + CountDownLatch serverStartedLatch = new CountDownLatch(1); client.setSocketFactory(new TestSocketFactory(bindingAddress)); @@ -131,14 +136,16 @@ public void onError(WebSocket conn, Exception ex) { @Override public void onStart() { + serverStartedLatch.countDown(); } }; server.start(); + serverStartedLatch.await(); client.connectBlocking(); - Assert.assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); - Assert.assertNotEquals(0, client.getSocket().getLocalPort()); - Assert.assertTrue(client.getSocket().isConnected()); + assertEquals(bindingAddress, client.getSocket().getLocalAddress().getHostAddress()); + assertNotEquals(0, client.getSocket().getLocalPort()); + assertTrue(client.getSocket().isConnected()); } } diff --git a/src/test/java/org/java_websocket/issues/Issue997Test.java b/src/test/java/org/java_websocket/issues/Issue997Test.java index be227cef7..e72a338c2 100644 --- a/src/test/java/org/java_websocket/issues/Issue997Test.java +++ b/src/test/java/org/java_websocket/issues/Issue997Test.java @@ -27,9 +27,6 @@ */ -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; @@ -44,6 +41,7 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLParameters; + import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ClientHandshake; @@ -52,161 +50,171 @@ import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SSLContextUtil; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class Issue997Test { - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_Client127_CheckActive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), - "HTTPS"); - assertFalse(client.onOpen); - assertTrue(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_Client127_CheckInactive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_Client127_CheckDefault() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); - assertFalse(client.onOpen); - assertTrue(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), - "HTTPS"); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - @Test(timeout = 2000) - public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() - throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { - SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), - SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); - assertTrue(client.onOpen); - assertFalse(client.onSSLError); - } - - - public SSLWebSocketClient testIssueWithLocalServer(String address, int port, - SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) - throws IOException, URISyntaxException, InterruptedException { - CountDownLatch countServerDownLatch = new CountDownLatch(1); - SSLWebSocketClient client = new SSLWebSocketClient(address, port, - endpointIdentificationAlgorithm); - WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); - - server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); - if (clientContext != null) { - client.setSocketFactory(clientContext.getSocketFactory()); + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_Client127_CheckActive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), + "HTTPS"); + assertFalse(client.onOpen, "client is not open"); + assertTrue(client.onSSLError, "client has caught a SSLHandshakeException"); } - server.start(); - countServerDownLatch.await(); - client.connectBlocking(1, TimeUnit.SECONDS); - return client; - } - - - private static class SSLWebSocketClient extends WebSocketClient { - private final String endpointIdentificationAlgorithm; - public boolean onSSLError = false; - public boolean onOpen = false; - - public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) - throws URISyntaxException { - super(new URI("wss://" + address + ':' + port)); - this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_Client127_CheckInactive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - public void onOpen(ServerHandshake handshakedata) { - this.onOpen = true; + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_Client127_CheckDefault() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("127.0.0.1", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertFalse(client.onOpen, "client is not open"); + assertTrue(client.onSSLError, "client has caught a SSLHandshakeException"); } - @Override - public void onMessage(String message) { + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckActive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), + "HTTPS"); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - public void onClose(int code, String reason, boolean remote) { + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckInactive() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), ""); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - public void onError(Exception ex) { - if (ex instanceof SSLHandshakeException) { - this.onSSLError = true; - } + @Test + @Timeout(2000) + public void test_localServer_ServerLocalhost_ClientLocalhost_CheckDefault() + throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, IOException, URISyntaxException, InterruptedException { + SSLWebSocketClient client = testIssueWithLocalServer("localhost", SocketUtil.getAvailablePort(), + SSLContextUtil.getLocalhostOnlyContext(), SSLContextUtil.getLocalhostOnlyContext(), null); + assertTrue(client.onOpen, "client is open"); + assertFalse(client.onSSLError, "client has not caught a SSLHandshakeException"); } - @Override - protected void onSetSSLParameters(SSLParameters sslParameters) { - // Always call super to ensure hostname validation is active by default - super.onSetSSLParameters(sslParameters); - if (endpointIdentificationAlgorithm != null) { - sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); - } + + public SSLWebSocketClient testIssueWithLocalServer(String address, int port, + SSLContext serverContext, SSLContext clientContext, String endpointIdentificationAlgorithm) + throws IOException, URISyntaxException, InterruptedException { + CountDownLatch countServerDownLatch = new CountDownLatch(1); + SSLWebSocketClient client = new SSLWebSocketClient(address, port, + endpointIdentificationAlgorithm); + WebSocketServer server = new SSLWebSocketServer(port, countServerDownLatch); + + server.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(serverContext)); + if (clientContext != null) { + client.setSocketFactory(clientContext.getSocketFactory()); + } + server.start(); + countServerDownLatch.await(); + client.connectBlocking(1, TimeUnit.SECONDS); + return client; } - } + private static class SSLWebSocketClient extends WebSocketClient { - private static class SSLWebSocketServer extends WebSocketServer { + private final String endpointIdentificationAlgorithm; + public boolean onSSLError = false; + public boolean onOpen = false; - private final CountDownLatch countServerDownLatch; + public SSLWebSocketClient(String address, int port, String endpointIdentificationAlgorithm) + throws URISyntaxException { + super(new URI("wss://" + address + ':' + port)); + this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm; + } + @Override + public void onOpen(ServerHandshake handshakedata) { + this.onOpen = true; + } - public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { - super(new InetSocketAddress(port)); - this.countServerDownLatch = countServerDownLatch; - } + @Override + public void onMessage(String message) { + } - @Override - public void onOpen(WebSocket conn, ClientHandshake handshake) { - } + @Override + public void onClose(int code, String reason, boolean remote) { + } - @Override - public void onClose(WebSocket conn, int code, String reason, boolean remote) { - } + @Override + public void onError(Exception ex) { + if (ex instanceof SSLHandshakeException) { + this.onSSLError = true; + } + } - @Override - public void onMessage(WebSocket conn, String message) { + @Override + protected void onSetSSLParameters(SSLParameters sslParameters) { + // Always call super to ensure hostname validation is active by default + super.onSetSSLParameters(sslParameters); + if (endpointIdentificationAlgorithm != null) { + sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm); + } + } } - @Override - public void onError(WebSocket conn, Exception ex) { - ex.printStackTrace(); - } - @Override - public void onStart() { - countServerDownLatch.countDown(); + private static class SSLWebSocketServer extends WebSocketServer { + + private final CountDownLatch countServerDownLatch; + + + public SSLWebSocketServer(int port, CountDownLatch countServerDownLatch) { + super(new InetSocketAddress(port)); + this.countServerDownLatch = countServerDownLatch; + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + } + + @Override + public void onMessage(WebSocket conn, String message) { + + } + + @Override + public void onError(WebSocket conn, Exception ex) { + ex.printStackTrace(); + } + + @Override + public void onStart() { + countServerDownLatch.countDown(); + } } - } } diff --git a/src/test/java/org/java_websocket/misc/AllMiscTests.java b/src/test/java/org/java_websocket/misc/AllMiscTests.java deleted file mode 100644 index bd643c093..000000000 --- a/src/test/java/org/java_websocket/misc/AllMiscTests.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.misc; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.misc.OpeningHandshakeRejectionTest.class -}) -/** - * Start all tests for mics - */ -public class AllMiscTests { - -} diff --git a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java index fe1805c1e..8290d5244 100644 --- a/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/misc/OpeningHandshakeRejectionTest.java @@ -25,247 +25,265 @@ package org.java_websocket.misc; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.URI; import java.util.Scanner; +import java.util.concurrent.CountDownLatch; + import org.java_websocket.client.WebSocketClient; import org.java_websocket.framing.CloseFrame; import org.java_websocket.handshake.ServerHandshake; import org.java_websocket.util.Charsetfunctions; import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.*; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class OpeningHandshakeRejectionTest { - private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; - private static int counter = 0; - private static Thread thread; - private static ServerSocket serverSocket; + private int port = -1; + private Thread thread; + private ServerSocket serverSocket; - private static boolean debugPrintouts = false; + private static final String additionalHandshake = "Upgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; - private static int port; + public void startServer() throws InterruptedException { + this.port = SocketUtil.getAvailablePort(); + this.thread = new Thread( + () -> { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + if (!in.hasNextLine()) { + continue; + } + String input = in.nextLine(); + String testCase = input.split(" ")[1]; + OutputStream os = client.getOutputStream(); + if ("/0".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/1".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.0 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/2".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP 100 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/3".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 200 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/4".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/5".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 404 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/6".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/2.0 404 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/7".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 500 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/8".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("GET 302 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/9".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + "GET HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/10".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes("HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); + os.flush(); + } + if ("/11".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + "HTTP/1.1 101 Websocket Connection Upgrade\r\n" + additionalHandshake)); + os.flush(); + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + fail("There should not be an exception: " + e.getMessage() + " Port: " + port); + } + }); + this.thread.start(); + } - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket(port); - serverSocket.setReuseAddress(true); - while (true) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner(client.getInputStream()); - String input = in.nextLine(); - String testCase = input.split(" ")[1]; - OutputStream os = client.getOutputStream(); - if ("/0".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 100 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/1".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.0 100 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/2".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP 100 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/3".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 200 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/4".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP 101 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/5".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 404 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/6".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/2.0 404 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/7".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 500 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/8".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("GET 302 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/9".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - "GET HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/10".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes("HTTP/1.1 101 Switching Protocols\r\n" + additionalHandshake)); - os.flush(); - } - if ("/11".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - "HTTP/1.1 101 Websocket Connection Upgrade\r\n" + additionalHandshake)); - os.flush(); - } - } catch (IOException e) { - // - } - } - } catch (Exception e) { - fail("There should be no exception"); - } - } - }); - thread.start(); - } + @AfterEach + public void cleanUp() throws IOException { + if (serverSocket != null) { + serverSocket.close(); + } + if (thread != null) { + thread.interrupt(); + } + } - @AfterClass - public static void successTests() throws InterruptedException, IOException { - serverSocket.close(); - thread.interrupt(); - if (debugPrintouts) { - System.out.println(counter + " successful tests"); + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase0() throws Exception { + testHandshakeRejection(0); } - } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase0() throws Exception { - testHandshakeRejection(0); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase1() throws Exception { + testHandshakeRejection(1); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase1() throws Exception { - testHandshakeRejection(1); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase2() throws Exception { + testHandshakeRejection(2); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase2() throws Exception { - testHandshakeRejection(2); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase3() throws Exception { + testHandshakeRejection(3); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase3() throws Exception { - testHandshakeRejection(3); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase4() throws Exception { + testHandshakeRejection(4); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase4() throws Exception { - testHandshakeRejection(4); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase5() throws Exception { + testHandshakeRejection(5); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase5() throws Exception { - testHandshakeRejection(5); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase6() throws Exception { + testHandshakeRejection(6); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase6() throws Exception { - testHandshakeRejection(6); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase7() throws Exception { + testHandshakeRejection(7); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase7() throws Exception { - testHandshakeRejection(7); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase8() throws Exception { + testHandshakeRejection(8); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase8() throws Exception { - testHandshakeRejection(8); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase9() throws Exception { + testHandshakeRejection(9); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase9() throws Exception { - testHandshakeRejection(9); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase10() throws Exception { + testHandshakeRejection(10); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase10() throws Exception { - testHandshakeRejection(10); - } + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase11() throws Exception { + testHandshakeRejection(11); + } - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase11() throws Exception { - testHandshakeRejection(11); - } + private void testHandshakeRejection(int i) throws Exception { + startServer(); + assertTrue(SocketUtil.waitForServerToStart(this.port), "Server Start Status"); + final int finalI = i; + final CountDownLatch countDownLatch = new CountDownLatch(1); + WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + this.port + "/" + finalI)) { + @Override + public void onOpen(ServerHandshake handshakedata) { + fail("There should not be a connection!"); + } - private void testHandshakeRejection(int i) throws Exception { - final int finalI = i; - final boolean[] threadReturned = {false}; - WebSocketClient webSocketClient = new WebSocketClient( - new URI("ws://localhost:" + port + "/" + finalI)) { - @Override - public void onOpen(ServerHandshake handshakedata) { - fail("There should not be a connection!"); - } + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } - @Override - public void onMessage(String message) { - fail("There should not be a message!"); - } + @Override + public void onClose(int code, String reason, boolean remote) { + if (finalI != 10 && finalI != 11) { + if (code != CloseFrame.PROTOCOL_ERROR) { + fail("There should be a protocol error!"); + } else if (reason.startsWith("Invalid status code received:") || reason + .startsWith("Invalid status line received:")) { + countDownLatch.countDown(); + } else { + fail("The reason should be included!"); + } + } else { + //Since we do not include a correct Sec-WebSocket-Accept, onClose will be called with reason 'Draft refuses handshake' + if (!reason.endsWith("refuses handshake")) { + fail("onClose should not be called!"); + } else { + countDownLatch.countDown(); + } + } + } - @Override - public void onClose(int code, String reason, boolean remote) { - if (finalI != 10 && finalI != 11) { - if (code != CloseFrame.PROTOCOL_ERROR) { - fail("There should be a protocol error!"); - } else if (reason.startsWith("Invalid status code received:") || reason - .startsWith("Invalid status line received:")) { - if (debugPrintouts) { - System.out.println("Protocol error for test case: " + finalI); + @Override + public void onError(Exception ex) { + fail("There should not be an exception: " + ex.getMessage() + " Port: " + port); } - threadReturned[0] = true; - counter++; - } else { - fail("The reason should be included!"); - } - } else { - //Since we do not include a correct Sec-WebSocket-Accept, onClose will be called with reason 'Draft refuses handshake' - if (!reason.endsWith("refuses handshake")) { - fail("onClose should not be called!"); - } else { - if (debugPrintouts) { - System.out.println("Refuses handshake error for test case: " + finalI); + }; + final AssertionError[] exc = new AssertionError[1]; + exc[0] = null; + Thread finalThread = new Thread(new Runnable() { + @Override + public void run() { + try { + webSocketClient.run(); + } catch (AssertionError e) { + exc[0] = e; + countDownLatch.countDown(); + } } - counter++; - threadReturned[0] = true; - } - } - } - - @Override - public void onError(Exception ex) { - fail("There should not be an exception"); - } - }; - Thread finalThread = new Thread(webSocketClient); - finalThread.start(); - finalThread.join(); - if (!threadReturned[0]) { - fail("Error"); + }); + finalThread.start(); + finalThread.join(); + if (exc[0] != null) { + throw exc[0]; + } + countDownLatch.await(); } - } } diff --git a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java b/src/test/java/org/java_websocket/protocols/AllProtocolTests.java deleted file mode 100644 index 60c31ae02..000000000 --- a/src/test/java/org/java_websocket/protocols/AllProtocolTests.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.protocols; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.protocols.ProtocolTest.class, - ProtocolHandshakeRejectionTest.class -}) -/** - * Start all tests for protocols - */ -public class AllProtocolTests { - -} diff --git a/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java index f1249ff11..c8c1d69e3 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolHandshakeRejectionTest.java @@ -25,10 +25,6 @@ package org.java_websocket.protocols; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; @@ -39,6 +35,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; +import java.util.concurrent.CountDownLatch; + import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.extensions.IExtension; @@ -47,587 +45,621 @@ import org.java_websocket.util.Base64; import org.java_websocket.util.Charsetfunctions; import org.java_websocket.util.SocketUtil; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.*; + +import static org.junit.jupiter.api.Assertions.*; public class ProtocolHandshakeRejectionTest { - private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; - private static Thread thread; - private static ServerSocket serverSocket; - - private static int port; - - @BeforeClass - public static void startServer() throws Exception { - port = SocketUtil.getAvailablePort(); - thread = new Thread( - new Runnable() { - public void run() { - try { - serverSocket = new ServerSocket(port); - serverSocket.setReuseAddress(true); - while (true) { - Socket client = null; - try { - client = serverSocket.accept(); - Scanner in = new Scanner(client.getInputStream()); - String input = in.nextLine(); - String testCase = input.split(" ")[1]; - String seckey = ""; - String secproc = ""; - while (in.hasNext()) { - input = in.nextLine(); - if (input.startsWith("Sec-WebSocket-Key: ")) { - seckey = input.split(" ")[1]; - } - if (input.startsWith("Sec-WebSocket-Protocol: ")) { - secproc = input.split(" ")[1]; + private static final String additionalHandshake = "HTTP/1.1 101 Websocket Connection Upgrade\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"; + private Thread thread; + private ServerSocket serverSocket; + + private int port = -1; + + public void startServer() throws InterruptedException { + port = SocketUtil.getAvailablePort(); + thread = new Thread( + () -> { + try { + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + while (true) { + Socket client = null; + try { + client = serverSocket.accept(); + Scanner in = new Scanner(client.getInputStream()); + if (!in.hasNextLine()) { + continue; + } + String input = in.nextLine(); + String testCase = input.split(" ")[1]; + String seckey = ""; + String secproc = ""; + while (in.hasNext()) { + input = in.nextLine(); + if (input.startsWith("Sec-WebSocket-Key: ")) { + seckey = input.split(" ")[1]; + } + if (input.startsWith("Sec-WebSocket-Protocol: ")) { + secproc = input.split(" ")[1]; + } + //Last + if (input.startsWith("Upgrade")) { + break; + } + } + OutputStream os = client.getOutputStream(); + if ("/0".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/1".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/2".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); + os.flush(); + } + if ("/3".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/4".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/5".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/6".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/7".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); + os.flush(); + } + if ("/8".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/9".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/10".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/11".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2, chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/12".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/13".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat" + + "\r\n\r\n")); + os.flush(); + } + if ("/14".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat2,chat" + "\r\n\r\n")); + os.flush(); + } + if ("/15".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat3" + + "\r\n\r\n")); + os.flush(); + } + if ("/16".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/17".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); + os.flush(); + } + if ("/18".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + "Sec-WebSocket-Accept: abc\r\n" + "\r\n")); + os.flush(); + } + if ("/19".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + "\r\n")); + os.flush(); + } + // Order check + if ("/20".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/21".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/22".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/23".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/24".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/25".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" + + "\r\n\r\n")); + os.flush(); + } + if ("/26".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); + os.flush(); + } + if ("/27".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) + + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); + os.flush(); + } + if ("/28".equals(testCase)) { + os.write(Charsetfunctions.asciiBytes( + additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" + + "\r\n\r\n")); + os.flush(); + } + if ("/29".equals(testCase)) { + os.write(Charsetfunctions + .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); + os.flush(); + } + } catch (IOException e) { + // + } + } + } catch (Exception e) { + fail("There should be no exception", e); } - //Last - if (input.startsWith("Upgrade")) { - break; + }); + thread.start(); + } + + private static String getSecKey(String seckey) { + return "Sec-WebSocket-Accept: " + generateFinalKey(seckey) + "\r\n"; + } + + @AfterEach + public void successTests() throws IOException { + if (serverSocket != null) { + serverSocket.close(); + } + if (thread != null) { + thread.interrupt(); + } + } + + @Test + @Timeout(5000) + public void testProtocolRejectionTestCase0() throws Exception { + testProtocolRejection(0, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase1() throws Exception { + testProtocolRejection(1, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase2() throws Exception { + testProtocolRejection(2, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase3() throws Exception { + testProtocolRejection(3, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase4() throws Exception { + testProtocolRejection(4, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase5() throws Exception { + testProtocolRejection(5, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase6() throws Exception { + testProtocolRejection(6, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase7() throws Exception { + testProtocolRejection(7, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase8() throws Exception { + testProtocolRejection(8, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase9() throws Exception { + testProtocolRejection(9, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase10() throws Exception { + testProtocolRejection(10, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase11() throws Exception { + testProtocolRejection(11, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase12() throws Exception { + testProtocolRejection(12, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase13() throws Exception { + testProtocolRejection(13, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("chat")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase14() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(14, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase15() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(15, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase16() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("chat2")); + testProtocolRejection(16, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase17() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat")); + protocols.add(new Protocol("")); + testProtocolRejection(17, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase18() throws Exception { + testProtocolRejection(18, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase19() throws Exception { + testProtocolRejection(19, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase20() throws Exception { + testProtocolRejection(20, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase21() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat1")); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat3")); + testProtocolRejection(21, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase22() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("chat1")); + testProtocolRejection(22, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase23() throws Exception { + ArrayList protocols = new ArrayList<>(); + protocols.add(new Protocol("chat3")); + protocols.add(new Protocol("chat2")); + protocols.add(new Protocol("chat1")); + testProtocolRejection(23, new Draft_6455(Collections.emptyList(), protocols)); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase24() throws Exception { + testProtocolRejection(24, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase25() throws Exception { + testProtocolRejection(25, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase26() throws Exception { + testProtocolRejection(26, new Draft_6455()); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase27() throws Exception { + testProtocolRejection(27, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase28() throws Exception { + testProtocolRejection(28, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + @Test + @Timeout(5000) + public void testHandshakeRejectionTestCase29() throws Exception { + testProtocolRejection(29, new Draft_6455(Collections.emptyList(), + Collections.singletonList(new Protocol("opc")))); + } + + private void testProtocolRejection(int i, Draft_6455 draft) throws Exception { + startServer(); + assertTrue(SocketUtil.waitForServerToStart(this.port), "Server Start Status"); + final int finalI = i; + final CountDownLatch countDownLatch = new CountDownLatch(1); + final WebSocketClient webSocketClient = new WebSocketClient( + new URI("ws://localhost:" + port + "/" + finalI), draft) { + @Override + public void onOpen(ServerHandshake handshakedata) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + case 14: + case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + countDownLatch.countDown(); + closeConnection(CloseFrame.ABNORMAL_CLOSE, "Bye"); + break; + default: + fail("There should not be a connection!"); + } + } + + @Override + public void onMessage(String message) { + fail("There should not be a message!"); + } + + @Override + public void onClose(int code, String reason, boolean remote) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 17: + case 20: + case 24: + case 25: + case 26: + assertEquals("", getProtocol().getProvidedProtocol()); + break; + case 5: + case 9: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + case 18: + case 19: + case 27: + case 28: + case 29: + assertNull(getProtocol()); + break; + case 6: + case 7: + case 8: + case 14: + assertEquals("chat", getProtocol().getProvidedProtocol()); + break; + case 22: + assertEquals("chat2", getProtocol().getProvidedProtocol()); + break; + case 21: + assertEquals("chat1", getProtocol().getProvidedProtocol()); + break; + case 23: + assertEquals("chat3", getProtocol().getProvidedProtocol()); + break; + default: + fail(); + } + if (code == CloseFrame.ABNORMAL_CLOSE) { + switch (finalI) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 9: + case 13: + case 14: + case 17: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + return; } - } - OutputStream os = client.getOutputStream(); - if ("/0".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/1".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" - + "\r\n\r\n")); - os.flush(); - } - if ("/2".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); - os.flush(); - } - if ("/3".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/4".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/5".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/6".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat" - + "\r\n\r\n")); - os.flush(); - } - if ("/7".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat, chat2" + "\r\n\r\n")); - os.flush(); - } - if ("/8".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/9".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat\r\nSec-WebSocket-Protocol: chat2,chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/10".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/11".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2, chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/12".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/13".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2\r\nSec-WebSocket-Protocol: chat" - + "\r\n\r\n")); - os.flush(); - } - if ("/14".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat2,chat" + "\r\n\r\n")); - os.flush(); - } - if ("/15".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: chat3" - + "\r\n\r\n")); - os.flush(); - } - if ("/16".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/17".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n")); - os.flush(); - } - if ("/18".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + "Sec-WebSocket-Accept: abc\r\n" + "\r\n")); - os.flush(); - } - if ("/19".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + "\r\n")); - os.flush(); - } - // Order check - if ("/20".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/21".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/22".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/23".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/24".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/25".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" - + "\r\n\r\n")); - os.flush(); - } - if ("/26".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); - os.flush(); - } - if ("/27".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes(additionalHandshake + getSecKey(seckey) - + "Sec-WebSocket-Protocol: chat1,chat2,chat3" + "\r\n\r\n")); - os.flush(); - } - if ("/28".equals(testCase)) { - os.write(Charsetfunctions.asciiBytes( - additionalHandshake + getSecKey(seckey) + "Sec-WebSocket-Protocol: abc" - + "\r\n\r\n")); - os.flush(); - } - if ("/29".equals(testCase)) { - os.write(Charsetfunctions - .asciiBytes(additionalHandshake + getSecKey(seckey) + "\r\n\r\n")); - os.flush(); - } - } catch (IOException e) { - // } - } - } catch (Exception e) { - e.printStackTrace(); - fail("There should be no exception"); + if (code != CloseFrame.PROTOCOL_ERROR) { + fail("There should be a protocol error! " + finalI + " " + code); + } else if (reason.endsWith("refuses handshake")) { + countDownLatch.countDown(); + } else { + fail("The reason should be included!"); + } } - } + + @Override + public void onError(Exception ex) { + fail("There should not be an exception: " + ex.getMessage() + " Port: " + port); + } + }; + final AssertionError[] exc = new AssertionError[1]; + exc[0] = null; + Thread finalThread = new Thread(new Runnable() { + @Override + public void run() { + try { + webSocketClient.run(); + } catch (AssertionError e) { + exc[0] = e; + countDownLatch.countDown(); + } + } + }); - thread.start(); - } - - private static String getSecKey(String seckey) { - return "Sec-WebSocket-Accept: " + generateFinalKey(seckey) + "\r\n"; - } - - @AfterClass - public static void successTests() throws IOException { - serverSocket.close(); - thread.interrupt(); - } - - @Test(timeout = 5000) - public void testProtocolRejectionTestCase0() throws Exception { - testProtocolRejection(0, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase1() throws Exception { - testProtocolRejection(1, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase2() throws Exception { - testProtocolRejection(2, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase3() throws Exception { - testProtocolRejection(3, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase4() throws Exception { - testProtocolRejection(4, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase5() throws Exception { - testProtocolRejection(5, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase6() throws Exception { - testProtocolRejection(6, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase7() throws Exception { - testProtocolRejection(7, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase8() throws Exception { - testProtocolRejection(8, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase9() throws Exception { - testProtocolRejection(9, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase10() throws Exception { - testProtocolRejection(10, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase11() throws Exception { - testProtocolRejection(11, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase12() throws Exception { - testProtocolRejection(12, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase13() throws Exception { - testProtocolRejection(13, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("chat")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase14() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("chat2")); - testProtocolRejection(14, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase15() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("chat2")); - testProtocolRejection(15, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase16() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("chat2")); - testProtocolRejection(16, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase17() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat")); - protocols.add(new Protocol("")); - testProtocolRejection(17, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase18() throws Exception { - testProtocolRejection(18, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase19() throws Exception { - testProtocolRejection(19, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase20() throws Exception { - testProtocolRejection(20, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase21() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat1")); - protocols.add(new Protocol("chat2")); - protocols.add(new Protocol("chat3")); - testProtocolRejection(21, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase22() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat2")); - protocols.add(new Protocol("chat3")); - protocols.add(new Protocol("chat1")); - testProtocolRejection(22, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase23() throws Exception { - ArrayList protocols = new ArrayList<>(); - protocols.add(new Protocol("chat3")); - protocols.add(new Protocol("chat2")); - protocols.add(new Protocol("chat1")); - testProtocolRejection(23, new Draft_6455(Collections.emptyList(), protocols)); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase24() throws Exception { - testProtocolRejection(24, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase25() throws Exception { - testProtocolRejection(25, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase26() throws Exception { - testProtocolRejection(26, new Draft_6455()); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase27() throws Exception { - testProtocolRejection(27, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("opc")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase28() throws Exception { - testProtocolRejection(28, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("opc")))); - } - - @Test(timeout = 5000) - public void testHandshakeRejectionTestCase29() throws Exception { - testProtocolRejection(29, new Draft_6455(Collections.emptyList(), - Collections.singletonList(new Protocol("opc")))); - } - - private void testProtocolRejection(int i, Draft_6455 draft) throws Exception { - final int finalI = i; - final boolean[] threadReturned = {false}; - final WebSocketClient webSocketClient = new WebSocketClient( - new URI("ws://localhost:" + port + "/" + finalI), draft) { - @Override - public void onOpen(ServerHandshake handshakedata) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 13: - case 14: - case 17: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - threadReturned[0] = true; - closeConnection(CloseFrame.ABNORMAL_CLOSE, "Bye"); - break; - default: - fail("There should not be a connection!"); - } - } - - @Override - public void onMessage(String message) { - fail("There should not be a message!"); - } - - @Override - public void onClose(int code, String reason, boolean remote) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 17: - case 20: - case 24: - case 25: - case 26: - assertEquals("", getProtocol().getProvidedProtocol()); - break; - case 5: - case 9: - case 10: - case 11: - case 12: - case 13: - case 15: - case 16: - case 18: - case 19: - case 27: - case 28: - case 29: - assertNull(getProtocol()); - break; - case 6: - case 7: - case 8: - case 14: - assertEquals("chat", getProtocol().getProvidedProtocol()); - break; - case 22: - assertEquals("chat2", getProtocol().getProvidedProtocol()); - break; - case 21: - assertEquals("chat1", getProtocol().getProvidedProtocol()); - break; - case 23: - assertEquals("chat3", getProtocol().getProvidedProtocol()); - break; - default: - fail(); - } - if (code == CloseFrame.ABNORMAL_CLOSE) { - switch (finalI) { - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 13: - case 14: - case 17: - case 20: - case 21: - case 22: - case 23: - case 24: - case 25: - case 26: - return; - } - } - if (code != CloseFrame.PROTOCOL_ERROR) { - fail("There should be a protocol error! " + finalI + " " + code); - } else if (reason.endsWith("refuses handshake")) { - threadReturned[0] = true; - } else { - fail("The reason should be included!"); + finalThread.start(); + finalThread.join(); + if (exc[0] != null) { + throw exc[0]; } - } - - @Override - public void onError(Exception ex) { - fail("There should not be an exception"); - } - }; - final AssertionError[] exc = new AssertionError[1]; - exc[0] = null; - Thread finalThread = new Thread(new Runnable() { - @Override - public void run() { + + countDownLatch.await(); + + } + + /** + * Generate a final key from a input string + * + * @param in the input string + * @return a final key + */ + private static String generateFinalKey(String in) { + String seckey = in.trim(); + String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + MessageDigest sh1; try { - webSocketClient.run(); - }catch(AssertionError e){ - exc[0] = e; + sh1 = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); } - } - - }); - finalThread.start(); - finalThread.join(); - if (exc[0] != null) { - throw exc[0]; - } - - if (!threadReturned[0]) { - fail("Error"); - } - - } - - /** - * Generate a final key from a input string - * - * @param in the input string - * @return a final key - */ - private static String generateFinalKey(String in) { - String seckey = in.trim(); - String acc = seckey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - MessageDigest sh1; - try { - sh1 = MessageDigest.getInstance("SHA1"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException(e); - } - return Base64.encodeBytes(sh1.digest(acc.getBytes())); - } + return Base64.encodeBytes(sh1.digest(acc.getBytes())); + } } diff --git a/src/test/java/org/java_websocket/protocols/ProtocolTest.java b/src/test/java/org/java_websocket/protocols/ProtocolTest.java index e07119535..895b5a4f1 100644 --- a/src/test/java/org/java_websocket/protocols/ProtocolTest.java +++ b/src/test/java/org/java_websocket/protocols/ProtocolTest.java @@ -25,13 +25,9 @@ package org.java_websocket.protocols; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; public class ProtocolTest { @@ -94,11 +90,11 @@ public void testEquals() throws Exception { Protocol protocol0 = new Protocol(""); Protocol protocol1 = new Protocol("protocol"); Protocol protocol2 = new Protocol("protocol"); - assertTrue(!protocol0.equals(protocol1)); - assertTrue(!protocol0.equals(protocol2)); - assertTrue(protocol1.equals(protocol2)); - assertTrue(!protocol1.equals(null)); - assertTrue(!protocol1.equals(new Object())); + assertNotEquals(protocol0, protocol1); + assertNotEquals(protocol0, protocol2); + assertEquals(protocol1, protocol2); + assertNotEquals(null, protocol1); + assertNotEquals(new Object(), protocol1); } @Test diff --git a/src/test/java/org/java_websocket/server/AllServerTests.java b/src/test/java/org/java_websocket/server/AllServerTests.java deleted file mode 100644 index f1f84fc90..000000000 --- a/src/test/java/org/java_websocket/server/AllServerTests.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2010-2020 Nathan Rajlich - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -package org.java_websocket.server; - -import org.java_websocket.protocols.ProtocolHandshakeRejectionTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - org.java_websocket.server.DefaultWebSocketServerFactoryTest.class, - ProtocolHandshakeRejectionTest.class -}) -/** - * Start all tests for the server - */ -public class AllServerTests { - -} diff --git a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java index 1fa2d8a9a..a83d8de07 100644 --- a/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/CustomSSLWebSocketServerFactoryTest.java @@ -1,8 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -19,7 +16,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class CustomSSLWebSocketServerFactoryTest { @@ -82,10 +82,10 @@ public void testCreateWebSocket() throws NoSuchAlgorithmException { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); } @Test diff --git a/src/test/java/org/java_websocket/server/DaemonThreadTest.java b/src/test/java/org/java_websocket/server/DaemonThreadTest.java index f1b25c6f0..9047a97da 100644 --- a/src/test/java/org/java_websocket/server/DaemonThreadTest.java +++ b/src/test/java/org/java_websocket/server/DaemonThreadTest.java @@ -1,24 +1,27 @@ package org.java_websocket.server; -import java.io.IOException; import java.net.*; import java.util.Set; import java.util.concurrent.CountDownLatch; import org.java_websocket.WebSocket; import org.java_websocket.handshake.*; import org.java_websocket.client.*; -import org.java_websocket.server.WebSocketServer; import org.java_websocket.util.SocketUtil; -import org.junit.Test; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class DaemonThreadTest { - @Test(timeout = 1000) - public void test_AllCreatedThreadsAreDaemon() throws Throwable { + @Test + @Timeout(1000) + public void test_AllCreatedThreadsAreDaemon() throws InterruptedException { Set threadSet1 = Thread.getAllStackTraces().keySet(); final CountDownLatch ready = new CountDownLatch(1); + final CountDownLatch serverStarted = new CountDownLatch(1); WebSocketServer server = new WebSocketServer(new InetSocketAddress(SocketUtil.getAvailablePort())) { @Override @@ -30,12 +33,13 @@ public void onMessage(WebSocket conn, String message) {} @Override public void onError(WebSocket conn, Exception ex) {} @Override - public void onStart() {} + public void onStart() {serverStarted.countDown();} }; server.setDaemon(true); server.setDaemon(false); server.setDaemon(true); server.start(); + serverStarted.await(); WebSocketClient client = new WebSocketClient(URI.create("ws://localhost:" + server.getPort())) { @Override @@ -57,10 +61,10 @@ public void onError(Exception ex) {} Set threadSet2 = Thread.getAllStackTraces().keySet(); threadSet2.removeAll(threadSet1); - assertTrue("new threads created (no new threads indicates issue in test)", !threadSet2.isEmpty()); + assertFalse(threadSet2.isEmpty(), "new threads created (no new threads indicates issue in test)"); for (Thread t : threadSet2) - assertTrue(t.getName(), t.isDaemon()); + assertTrue(t.isDaemon(), t.getName()); boolean exception = false; try { @@ -68,7 +72,7 @@ public void onError(Exception ex) {} } catch(IllegalStateException e) { exception = true; } - assertTrue("exception was thrown when calling setDaemon on a running server", exception); + assertTrue(exception, "exception was thrown when calling setDaemon on a running server"); server.stop(); } diff --git a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java index 7872697ba..c8330a551 100644 --- a/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultSSLWebSocketServerFactoryTest.java @@ -1,8 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -19,7 +16,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class DefaultSSLWebSocketServerFactoryTest { @@ -62,10 +62,10 @@ public void testCreateWebSocket() throws NoSuchAlgorithmException { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl,"webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull( webSocketImpl, "webSocketImpl != null"); } @Test diff --git a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java index a5c07ea43..77dafa56f 100644 --- a/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/DefaultWebSocketServerFactoryTest.java @@ -1,7 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; import java.net.InetSocketAddress; import java.net.Socket; @@ -14,7 +12,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; public class DefaultWebSocketServerFactoryTest { @@ -24,10 +25,10 @@ public void testCreateWebSocket() { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); } @Test @@ -35,7 +36,7 @@ public void testWrapChannel() { DefaultWebSocketServerFactory webSocketServerFactory = new DefaultWebSocketServerFactory(); SocketChannel channel = (new Socket()).getChannel(); SocketChannel result = webSocketServerFactory.wrapChannel(channel, null); - assertSame("channel == result", channel, result); + assertSame(channel, result, "channel == result"); } @Test diff --git a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java index 5ac83337d..00715d231 100644 --- a/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java +++ b/src/test/java/org/java_websocket/server/SSLParametersWebSocketServerFactoryTest.java @@ -1,8 +1,5 @@ package org.java_websocket.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -20,7 +17,10 @@ import org.java_websocket.drafts.Draft; import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.Handshakedata; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public class SSLParametersWebSocketServerFactoryTest { @@ -57,10 +57,10 @@ public void testCreateWebSocket() throws NoSuchAlgorithmException { CustomWebSocketAdapter webSocketAdapter = new CustomWebSocketAdapter(); WebSocketImpl webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, new Draft_6455()); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); webSocketImpl = webSocketServerFactory .createWebSocket(webSocketAdapter, Collections.singletonList(new Draft_6455())); - assertNotNull("webSocketImpl != null", webSocketImpl); + assertNotNull(webSocketImpl, "webSocketImpl != null"); } @Test diff --git a/src/test/java/org/java_websocket/server/WebSocketServerTest.java b/src/test/java/org/java_websocket/server/WebSocketServerTest.java index 5bebf8028..9af9d10e8 100644 --- a/src/test/java/org/java_websocket/server/WebSocketServerTest.java +++ b/src/test/java/org/java_websocket/server/WebSocketServerTest.java @@ -26,9 +26,6 @@ package org.java_websocket.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; import java.io.IOException; import java.net.InetSocketAddress; @@ -43,7 +40,9 @@ import org.java_websocket.drafts.Draft_6455; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.util.SocketUtil; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class WebSocketServerTest { @@ -111,7 +110,7 @@ public void testConstructor() { @Test - public void testGetAddress() throws IOException { + public void testGetAddress() throws InterruptedException { int port = SocketUtil.getAvailablePort(); InetSocketAddress inetSocketAddress = new InetSocketAddress(port); MyWebSocketServer server = new MyWebSocketServer(port); @@ -145,9 +144,9 @@ public void testGetPort() throws IOException, InterruptedException { @Test public void testMaxPendingConnections() { MyWebSocketServer server = new MyWebSocketServer(1337); - assertEquals(server.getMaxPendingConnections(), -1); + assertEquals(-1, server.getMaxPendingConnections()); server.setMaxPendingConnections(10); - assertEquals(server.getMaxPendingConnections(), 10); + assertEquals(10, server.getMaxPendingConnections()); } @Test diff --git a/src/test/java/org/java_websocket/util/Base64Test.java b/src/test/java/org/java_websocket/util/Base64Test.java index 4382aab60..0d546db50 100644 --- a/src/test/java/org/java_websocket/util/Base64Test.java +++ b/src/test/java/org/java_websocket/util/Base64Test.java @@ -25,27 +25,24 @@ package org.java_websocket.util; +import org.junit.jupiter.api.Test; + import java.io.IOException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -public class Base64Test { +import static org.junit.jupiter.api.Assertions.*; - @Rule - public final ExpectedException thrown = ExpectedException.none(); +public class Base64Test { @Test public void testEncodeBytes() throws IOException { - Assert.assertEquals("", Base64.encodeBytes(new byte[0])); - Assert.assertEquals("QHE=", + assertEquals("", Base64.encodeBytes(new byte[0])); + assertEquals("QHE=", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 0)); assertGzipEncodedBytes("H4sIAAAAAAAA", "MEALfv3IMBAAAA", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 0, 1, 6)); assertGzipEncodedBytes("H4sIAAAAAAAA", "MoBABQHKKWAgAAAA==", Base64.encodeBytes(new byte[]{49, 121, 64, 113, -63, 43, -24, 62, 4, 48}, 2, 2, 18)); - Assert.assertEquals("F63=", + assertEquals("F63=", Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 32)); assertGzipEncodedBytes("6sg7--------", "Bc0-0F699L-V----==", Base64.encodeBytes(new byte[]{49, 121, 64, 113, 63, 43, -24, 62, 4, 48}, 2, 2, 34)); @@ -53,57 +50,56 @@ public void testEncodeBytes() throws IOException { // see https://bugs.openjdk.org/browse/JDK-8253142 private void assertGzipEncodedBytes(String expectedPrefix, String expectedSuffix, String actual) { - Assert.assertTrue(actual.startsWith(expectedPrefix)); - Assert.assertTrue(actual.endsWith(expectedSuffix)); + assertTrue(actual.startsWith(expectedPrefix)); + assertTrue(actual.endsWith(expectedSuffix)); } @Test - public void testEncodeBytes2() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(new byte[0], -2, -2, -56); + public void testEncodeBytes2() { + assertThrows(IllegalArgumentException.class, () -> + Base64.encodeBytes(new byte[0], -2, -2, -56)); } @Test - public void testEncodeBytes3() throws IOException { - thrown.expect(IllegalArgumentException.class); + public void testEncodeBytes3() { + assertThrows(IllegalArgumentException.class, () -> Base64.encodeBytes(new byte[]{64, -128, 32, 18, 16, 16, 0, 18, 16}, - 2064072977, -2064007440, 10); + 2064072977, -2064007440, 10)); } @Test public void testEncodeBytes4() { - thrown.expect(NullPointerException.class); - Base64.encodeBytes(null); + assertThrows(NullPointerException.class, () -> Base64.encodeBytes(null)); } @Test - public void testEncodeBytes5() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytes(null, 32766, 0, 8); + public void testEncodeBytes5() { + assertThrows(IllegalArgumentException.class, () -> + Base64.encodeBytes(null, 32766, 0, 8)); } @Test public void testEncodeBytesToBytes1() throws IOException { - Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 45, 61, 61}, + assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 45, 61, 61}, Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32}, 0, 4, 32)); - Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, + assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32, -35}, 0, 5, 40)); - Assert.assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, + assertArrayEquals(new byte[]{95, 68, 111, 78, 55, 67, 111, 61}, Base64.encodeBytesToBytes(new byte[]{-108, -19, 24, 32, -35}, 0, 5, 32)); - Assert.assertArrayEquals(new byte[]{87, 50, 77, 61}, + assertArrayEquals(new byte[]{87, 50, 77, 61}, Base64.encodeBytesToBytes(new byte[]{115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 48)); - Assert.assertArrayEquals(new byte[]{87, 50, 77, 61}, + assertArrayEquals(new byte[]{87, 50, 77, 61}, Base64.encodeBytesToBytes(new byte[]{115, 42, 123, 99, 10, -33, 75, 30, 91, 99}, 8, 2, 56)); - Assert.assertArrayEquals(new byte[]{76, 53, 66, 61}, + assertArrayEquals(new byte[]{76, 53, 66, 61}, Base64.encodeBytesToBytes(new byte[]{113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 36)); - Assert.assertArrayEquals(new byte[]{87, 71, 77, 61}, + assertArrayEquals(new byte[]{87, 71, 77, 61}, Base64.encodeBytesToBytes(new byte[]{113, 42, 123, 99, 10, -33, 75, 30, 88, 99}, 8, 2, 4)); } @Test - public void testEncodeBytesToBytes2() throws IOException { - thrown.expect(IllegalArgumentException.class); - Base64.encodeBytesToBytes(new byte[]{83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26); + public void testEncodeBytesToBytes2() { + assertThrows(IllegalArgumentException.class, () -> + Base64.encodeBytesToBytes(new byte[]{83, 10, 91, 67, 42, -1, 107, 62, 91, 67}, 8, 6, 26)); } @Test @@ -129,6 +125,6 @@ public void testEncodeBytesToBytes3() throws IOException { 119, 61 }; - Assert.assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); + assertArrayEquals(excepted, Base64.encodeBytesToBytes(src, 0, 62, 8)); } } diff --git a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java index 40523418e..a694bac31 100644 --- a/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java +++ b/src/test/java/org/java_websocket/util/ByteBufferUtilsTest.java @@ -25,13 +25,11 @@ package org.java_websocket.util; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * JUnit Test for the new ByteBufferUtils class @@ -51,14 +49,14 @@ public class ByteBufferUtilsTest { @Test public void testEmptyByteBufferCapacity() { ByteBuffer byteBuffer = ByteBufferUtils.getEmptyByteBuffer(); - assertEquals("capacity must be 0", 0, byteBuffer.capacity()); + assertEquals( 0, byteBuffer.capacity(), "capacity must be 0"); } @Test public void testEmptyByteBufferNewObject() { ByteBuffer byteBuffer0 = ByteBufferUtils.getEmptyByteBuffer(); ByteBuffer byteBuffer1 = ByteBufferUtils.getEmptyByteBuffer(); - assertTrue("Allocated new object", byteBuffer0 != byteBuffer1); + assertNotSame(byteBuffer0, byteBuffer1, "Allocated new object"); } @Test @@ -66,8 +64,8 @@ public void testTransferByteBufferSmallToEmpty() { ByteBuffer small = ByteBuffer.wrap(smallArray); ByteBuffer empty = ByteBufferUtils.getEmptyByteBuffer(); ByteBufferUtils.transferByteBuffer(small, empty); - assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); - assertEquals("Capacity of the empty bytebuffer should still be 0", 0, empty.capacity()); + assertArrayEquals( smallArray, small.array(), "Small bytebuffer should not change"); + assertEquals( 0, empty.capacity(), "Capacity of the empty bytebuffer should still be 0"); } @Test @@ -75,16 +73,16 @@ public void testTransferByteBufferSmallToBig() { ByteBuffer small = ByteBuffer.wrap(smallArray); ByteBuffer big = ByteBuffer.wrap(bigArray); ByteBufferUtils.transferByteBuffer(small, big); - assertArrayEquals("Small bytebuffer should not change", smallArray, small.array()); - assertEquals("Big bytebuffer not same to source 0", smallArray[0], big.get(0)); - assertEquals("Big bytebuffer not same to source 1", smallArray[1], big.get(1)); - assertEquals("Big bytebuffer not same to source 2", smallArray[2], big.get(2)); - assertEquals("Big bytebuffer not same to source 3", smallArray[3], big.get(3)); - assertEquals("Big bytebuffer not same to source 4", smallArray[4], big.get(4)); - assertEquals("Big bytebuffer not same to source 5", bigArray[5], big.get(5)); - assertEquals("Big bytebuffer not same to source 6", bigArray[6], big.get(6)); - assertEquals("Big bytebuffer not same to source 7", bigArray[7], big.get(7)); - assertEquals("Big bytebuffer not same to source 8", bigArray[8], big.get(8)); + assertArrayEquals( smallArray, small.array(), "Small bytebuffer should not change"); + assertEquals( smallArray[0], big.get(0), "Big bytebuffer not same to source 0"); + assertEquals( smallArray[1], big.get(1), "Big bytebuffer not same to source 1"); + assertEquals( smallArray[2], big.get(2), "Big bytebuffer not same to source 2"); + assertEquals( smallArray[3], big.get(3), "Big bytebuffer not same to source 3"); + assertEquals( smallArray[4], big.get(4), "Big bytebuffer not same to source 4"); + assertEquals( bigArray[5], big.get(5), "Big bytebuffer not same to source 5"); + assertEquals( bigArray[6], big.get(6), "Big bytebuffer not same to source 6"); + assertEquals( bigArray[7], big.get(7), "Big bytebuffer not same to source 7"); + assertEquals( bigArray[8], big.get(8), "Big bytebuffer not same to source 8"); } @Test @@ -92,12 +90,12 @@ public void testTransferByteBufferBigToSmall() { ByteBuffer small = ByteBuffer.wrap(smallArray); ByteBuffer big = ByteBuffer.wrap(bigArray); ByteBufferUtils.transferByteBuffer(big, small); - assertArrayEquals("Big bytebuffer should not change", bigArray, big.array()); - assertEquals("Small bytebuffer not same to source 0", bigArray[0], small.get(0)); - assertEquals("Small bytebuffer not same to source 1", bigArray[1], small.get(1)); - assertEquals("Small bytebuffer not same to source 2", bigArray[2], small.get(2)); - assertEquals("Small bytebuffer not same to source 3", bigArray[3], small.get(3)); - assertEquals("Small bytebuffer not same to source 4", bigArray[4], small.get(4)); + assertArrayEquals( bigArray, big.array(), "Big bytebuffer should not change"); + assertEquals( bigArray[0], small.get(0), "Small bytebuffer not same to source 0"); + assertEquals( bigArray[1], small.get(1), "Small bytebuffer not same to source 1"); + assertEquals( bigArray[2], small.get(2), "Small bytebuffer not same to source 2"); + assertEquals( bigArray[3], small.get(3), "Small bytebuffer not same to source 3"); + assertEquals( bigArray[4], small.get(4), "Small bytebuffer not same to source 4"); } @Test diff --git a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java index 4d8ef3ae9..1a7ed29e1 100644 --- a/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java +++ b/src/test/java/org/java_websocket/util/CharsetfunctionsTest.java @@ -27,53 +27,54 @@ import java.nio.ByteBuffer; import org.java_websocket.exceptions.InvalidDataException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; public class CharsetfunctionsTest { @Test public void testAsciiBytes() { - Assert.assertArrayEquals(new byte[]{102, 111, 111}, Charsetfunctions.asciiBytes("foo")); + assertArrayEquals(new byte[]{102, 111, 111}, Charsetfunctions.asciiBytes("foo")); } @Test public void testStringUtf8ByteBuffer() throws InvalidDataException { - Assert.assertEquals("foo", + assertEquals("foo", Charsetfunctions.stringUtf8(ByteBuffer.wrap(new byte[]{102, 111, 111}))); } @Test public void testIsValidUTF8off() { - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 2)); - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}), 0)); + assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 2)); + assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}), 0)); - Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 0)); + assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}), 0)); } @Test public void testIsValidUTF8() { - Assert.assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}))); + assertFalse(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{(byte) 128}))); - Assert.assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}))); + assertTrue(Charsetfunctions.isValidUTF8(ByteBuffer.wrap(new byte[]{100}))); } @Test public void testStringAscii1() { - Assert.assertEquals("oBar", + assertEquals("oBar", Charsetfunctions.stringAscii(new byte[]{102, 111, 111, 66, 97, 114}, 2, 4)); } @Test public void testStringAscii2() { - Assert.assertEquals("foo", Charsetfunctions.stringAscii(new byte[]{102, 111, 111})); + assertEquals("foo", Charsetfunctions.stringAscii(new byte[]{102, 111, 111})); } @Test public void testUtf8Bytes() { - Assert.assertArrayEquals(new byte[]{102, 111, 111, 66, 97, 114}, + assertArrayEquals(new byte[]{102, 111, 111, 66, 97, 114}, Charsetfunctions.utf8Bytes("fooBar")); } } diff --git a/src/test/java/org/java_websocket/util/SocketUtil.java b/src/test/java/org/java_websocket/util/SocketUtil.java index e43c7fe3d..dd8d82a16 100644 --- a/src/test/java/org/java_websocket/util/SocketUtil.java +++ b/src/test/java/org/java_websocket/util/SocketUtil.java @@ -27,18 +27,40 @@ import java.io.IOException; import java.net.ServerSocket; +import java.net.Socket; public class SocketUtil { - public static int getAvailablePort() throws IOException { - ServerSocket srv = null; - try { - srv = new ServerSocket(0); - return srv.getLocalPort(); - } finally { - if (srv != null) { - srv.close(); - } + public static int getAvailablePort() throws InterruptedException { + while (true) { + try (ServerSocket srv = new ServerSocket(0)) { + return srv.getLocalPort(); + } catch (IOException e) { + // Retry + } + Thread.sleep(5); + } + } + public static boolean waitForServerToStart(int port) throws InterruptedException { + Socket socket = null; + for (int i = 0; i < 50; i++) { + try { + socket = new Socket("localhost", port); + if (socket.isConnected()) { + return true; + } + } catch (IOException ignore) { + // Ignore + } finally { + if (socket != null) { + try { + socket.close(); + } catch (IOException ignore) { + } + } + } + Thread.sleep(10); + } + return false; } - } } diff --git a/src/test/java/org/java_websocket/util/ThreadCheck.java b/src/test/java/org/java_websocket/util/ThreadCheck.java index 449a2b69d..208f8edcf 100644 --- a/src/test/java/org/java_websocket/util/ThreadCheck.java +++ b/src/test/java/org/java_websocket/util/ThreadCheck.java @@ -25,26 +25,33 @@ package org.java_websocket.util; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.Extension; +import org.junit.jupiter.api.extension.ExtensionContext; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.LockSupport; -import org.junit.Assert; -import org.junit.rules.ExternalResource; + +import static org.junit.jupiter.api.Assertions.fail; /** * Makes test fail if new threads are still alive after tear-down. */ -public class ThreadCheck extends ExternalResource { +public class ThreadCheck implements AfterEachCallback, BeforeEachCallback { private Map map = new HashMap(); @Override - protected void before() throws Throwable { + public void beforeEach(ExtensionContext context) throws Exception { map = getThreadMap(); } @Override - protected void after() { + public void afterEach(ExtensionContext context) throws Exception { long time = System.currentTimeMillis(); do { LockSupport.parkNanos(10000000); @@ -71,7 +78,7 @@ private boolean checkZombies(boolean testOnly) { } } if (zombies > 0 && !testOnly) { - Assert.fail("Found " + zombies + " zombie thread(s) "); + fail("Found " + zombies + " zombie thread(s) "); } return zombies > 0; @@ -82,7 +89,9 @@ public static Map getThreadMap() { Thread[] threads = new Thread[Thread.activeCount() * 2]; int actualNb = Thread.enumerate(threads); for (int i = 0; i < actualNb; i++) { - map.put(threads[i].getId(), threads[i]); + if (threads[i].getName().contains("WebSocket")) { + map.put(threads[i].getId(), threads[i]); + } } return map; } @@ -94,4 +103,6 @@ private static void appendStack(Thread th, StringBuilder s) { s.append(st[i]); } } + + }