From 34c2ce50ec30e2eb6fedbcb9770af23d62f46d58 Mon Sep 17 00:00:00 2001 From: Ingo Bauersachs Date: Mon, 4 Jan 2021 21:34:02 +0100 Subject: [PATCH] Migrate tests to JUnit 5 and release Maven Central (#221) * Migrate test to JUnit 5 and prepare POM for Maven Central * Use random ports for transaction tests * Apply ktlint format * Fix flaky tests * Use jicoco from Maven Central * Remove semver checks * Add Kotlin linting check * Use bnd-maven-plugin for OSGi to avoid confusing Kotlin * Release to Maven Central Closes #213 Closes #95 * Fix braces formatting that crept in with a regex --- .editorconfig | 9 + .github/workflows/maven.yml | 90 ++++ bnd.bnd | 6 + pom.xml | 261 +++++++++--- .../org/ice4j/attribute/AttributeDecoder.java | 4 +- .../ice/harvest/AbstractUdpListener.java | 5 +- src/main/java/org/ice4j/message/Message.java | 12 +- .../ice4j/stack/MessageProcessingTask.java | 4 +- src/main/kotlin/org/ice4j/ice/AgentConfig.kt | 3 +- .../org/ice4j/ice/harvest/HarvestConfig.kt | 7 +- .../ice4j/MessageEventDispatchingTest.java | 52 ++- src/test/java/org/ice4j/MsgFixture.java | 16 - .../java/org/ice4j/PseudoTcpTestSuite.java | 62 --- src/test/java/org/ice4j/StunTestSuite.java | 94 ----- .../org/ice4j/TransactionSupportTests.java | 102 ++--- .../ice4j/attribute/AddressAttributeTest.java | 250 ++++++----- .../ice4j/attribute/AttributeDecoderTest.java | 70 ++-- .../attribute/ChangeRequestAttributeTest.java | 117 +++--- .../attribute/ConnectionIdAttributeTest.java | 84 ++-- .../attribute/ErrorCodeAttributeTest.java | 131 +++--- .../ice4j/attribute/NonceAttributeTest.java | 53 +-- .../OptionalAttributeAttributeTest.java | 58 ++- .../ice4j/attribute/RealmAttributeTest.java | 51 +-- .../RequestedAddressFamilyAttributeTest.java | 118 ++---- .../attribute/SoftwareAttributeTest.java | 51 +-- .../UnknownAttributesAttributeTest.java | 162 ++++--- .../attribute/UsernameAttributeTest.java | 51 +-- .../java/org/ice4j/attribute/XorOnlyTest.java | 37 +- .../java/org/ice4j/ice/NetworkUtilsTest.java | 4 +- .../ice4j/ice/RoleConflictResolutionTest.java | 394 +++++++++--------- .../harvest/SinglePortUdpHarvesterTest.java | 23 +- .../org/ice4j/message/MessageFactoryTest.java | 66 ++- .../java/org/ice4j/message/MessageTest.java | 125 +++--- .../pseudotcp/MultiThreadSupportTest.java | 51 +-- .../ice4j/pseudotcp/PseudoTcpStreamTest.java | 123 ++---- .../pseudotcp/PseudoTcpTestPingPong.java | 36 +- .../pseudotcp/PseudoTcpTestRecvWindow.java | 23 +- .../pseudotcp/PseudoTcpTestTransfer.java | 43 +- .../pseudotcp/util/ByteFifoBufferTest.java | 31 +- .../jdk8/MuxServerSocketChannelTest.java | 32 ++ .../org/ice4j/stack/ShallowStackTest.java | 142 +++---- .../stunclient/StunAddressDiscovererTest.java | 73 ++-- .../StunAddressDiscovererTest_v4v6.java | 66 ++- .../StunAddressDiscovererTest_v6.java | 80 ++-- .../org/ice4j/util/PeriodicRunnableTests.java | 125 +++--- src/test/kotlin/org/ice4j/ConfigTest.kt | 2 +- .../kotlin/org/ice4j/ice/AgentConfigTest.kt | 3 +- .../jdk8/MuxServerSocketChannelTest.java | 44 -- 48 files changed, 1615 insertions(+), 1831 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/workflows/maven.yml create mode 100644 bnd.bnd delete mode 100644 src/test/java/org/ice4j/PseudoTcpTestSuite.java delete mode 100644 src/test/java/org/ice4j/StunTestSuite.java create mode 100644 src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java delete mode 100644 test/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9ae523a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 + +[pom.xml] +indent_size = 2 +indent_style = space +max_line_length = 120 diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..55fd9fd --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,90 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java CI with Maven + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + # Java version to use for the release + RELEASE_JAVA_VERSION: 8 + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + java: [ 8, 11 ] + + name: Java ${{ matrix.java }} + + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Set up JDK ${{ matrix.java }} + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + + - name: Cache local Maven repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Build and test with Maven + run: mvn -B -Dgpg.skip -Drelease=true verify + + release: + if: github.ref == 'refs/heads/master' + needs: test + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Set up JDK + uses: actions/setup-java@v1 + with: + java-version: ${{ env.RELEASE_JAVA_VERSION }} + server-id: ossrh + server-username: SONATYPE_USER + server-password: SONATYPE_PW + + - name: Cache local Maven repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Set version + run: | + VERSION=`git describe --match "v[0-9\.]*" --long --dirty --always` + mvn -B versions:set -DnewVersion=${VERSION:1} -DgenerateBackupPoms=false + + - name: Release to Maven Central + env: + SONATYPE_USER: ${{ secrets.SONATYPE_USER }} + SONATYPE_PW: ${{ secrets.SONATYPE_PW }} + run: | + cat <(echo -e "${{ secrets.GPG_KEY }}") | gpg --batch --import + gpg --list-secret-keys --keyid-format LONG + mvn \ + --no-transfer-progress \ + --batch-mode \ + -Dgpg.passphrase="${{ secrets.GPG_PW }}" \ + -Drelease=true \ + -DskipTests \ + deploy diff --git a/bnd.bnd b/bnd.bnd new file mode 100644 index 0000000..7933051 --- /dev/null +++ b/bnd.bnd @@ -0,0 +1,6 @@ +Export-Package: org.ice4j.* +Import-Package: *;version=! +Bundle-SymbolicName: org.jitsi.ice4j +-noextraheaders: true +-snapshot: SNAPSHOT +-removeheaders: Require-Capability, Bundle-SCM diff --git a/pom.xml b/pom.xml index 8477c9b..435e523 100644 --- a/pom.xml +++ b/pom.xml @@ -4,22 +4,45 @@ org.jitsi ice4j 3.0-SNAPSHOT - bundle ice4j + A Java implementation of the ICE protocol https://github.com/jitsi/ice4j + + + jitsi.org + https://jitsi.org + + + + + org.jitsi + Jitsi Team + dev@jitsi.org + + + https://github.com/jitsi/ice4j scm:git:https://github.com/jitsi/ice4j.git scm:git:https://github.com/jitsi/ice4j.git - HEAD + + + Apache-2.0 + https://github.com/jitsi/ice4j/blob/master/LICENSE + repo + + + UTF-8 - 1.1-53-gdc63c67 + 1.1-73-gf8e9405 1.3.72 4.1.3 + 5.7.0 + 1.4.20 @@ -36,7 +59,7 @@ ${project.groupId} jitsi-utils - 1.0-59-g5dc2b5f + 1.0-72-gcf6d1f8 ${project.groupId} @@ -46,16 +69,22 @@ - junit - junit - 4.13.1 + org.junit.platform + junit-platform-launcher + 1.7.0 test - io.kotest - kotest-runner-junit5-jvm - ${kotest.version} - test + org.junit.jupiter + junit-jupiter-api + ${junit.version} + test + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + test io.kotest @@ -65,7 +94,7 @@ io.kotest - kotest-runner-console-jvm + kotest-runner-junit5-jvm ${kotest.version} test @@ -75,6 +104,12 @@ ${jicoco.version} test + + org.mockito + mockito-core + 3.6.28 + test + @@ -157,61 +192,71 @@ - org.apache.felix - maven-bundle-plugin - 3.0.1 - true + com.github.gantsign.maven + ktlint-maven-plugin + 1.7.0 + + + ${project.basedir}/src/main/kotlin + + + ${project.basedir}/src/test/kotlin + + + + + check + + check + + + + + + biz.aQute.bnd + bnd-maven-plugin + 5.2.0 + + + + bnd-process + + + org.apache.maven.plugins - maven-javadoc-plugin - 2.10.4 + maven-jar-plugin + 3.2.0 - private - true + + ${project.build.outputDirectory}/META-INF/MANIFEST.MF + org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + 2.22.2 - - **/*TestSuite.* - + **/* - com.github.siom79.japicmp - japicmp-maven-plugin - 0.14.0 + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true - - - ${project.build.directory}/${project.build.finalName}.jar - - - - - ${project.groupId} - ${project.artifactId} - 1.0.0 - - - - true - true - true - + ossrh + https://oss.sonatype.org/ + true - - - verify - - cmp - - - @@ -346,24 +391,104 @@ + + + release + + + release + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + generate-sources + + add-source + + + + src/main/kotlin + + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.1 + + + attach-sources + verify + + jar-no-fork + + + + + + org.jetbrains.dokka + dokka-maven-plugin + ${dokka.version} + + + package + + javadocJar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + + + + + + --pinentry-mode + loopback + + + + + + - + + + + jcenter + JCenter + https://jcenter.bintray.com/ + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + - jitsi-maven-repository-releases - default - Jitsi Maven Repository (Releases) - - true - - - false - - https://github.com/jitsi/jitsi-maven-repository/raw/master/releases/ + ossrh + https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - jitpack.io - https://jitpack.io - - + diff --git a/src/main/java/org/ice4j/attribute/AttributeDecoder.java b/src/main/java/org/ice4j/attribute/AttributeDecoder.java index 468e853..870b055 100644 --- a/src/main/java/org/ice4j/attribute/AttributeDecoder.java +++ b/src/main/java/org/ice4j/attribute/AttributeDecoder.java @@ -43,8 +43,8 @@ public class AttributeDecoder * @throws StunException if bytes is not a valid STUN attribute. */ public static Attribute decode(byte[] bytes, - char offset, - char length) + int offset, + int length) throws StunException { if(bytes == null || bytes.length < Attribute.HEADER_LENGTH) diff --git a/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java b/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java index f4171dd..ae16371 100644 --- a/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java +++ b/src/main/java/org/ice4j/ice/harvest/AbstractUdpListener.java @@ -125,10 +125,7 @@ public abstract class AbstractUdpListener try { - Message stunMessage - = Message.decode(buf, - (char) off, - (char) len); + Message stunMessage = Message.decode(buf, off, len); if (stunMessage.getMessageType() != Message.BINDING_REQUEST) diff --git a/src/main/java/org/ice4j/message/Message.java b/src/main/java/org/ice4j/message/Message.java index a0bcb89..383f953 100644 --- a/src/main/java/org/ice4j/message/Message.java +++ b/src/main/java/org/ice4j/message/Message.java @@ -1057,11 +1057,11 @@ public abstract class Message * @throws StunException ILLEGAL_ARGUMENT if one or more of the * arguments have invalid values. */ - public static Message decode(byte binMessage[], char offset, char arrayLen) + public static Message decode(byte[] binMessage, int offset, int arrayLen) throws StunException { int originalOffset = offset; - arrayLen = (char)Math.min(binMessage.length, arrayLen); + arrayLen = Math.min(binMessage.length, arrayLen); if(arrayLen - offset < Message.HEADER_LENGTH) { @@ -1088,7 +1088,7 @@ public abstract class Message | (binMessage[offset++] & 0xFF)); /* copy the cookie */ - byte cookie[] = new byte[4]; + byte[] cookie = new byte[4]; System.arraycopy(binMessage, offset, cookie, 0, 4); offset += 4; @@ -1106,20 +1106,20 @@ public abstract class Message StunException.ILLEGAL_ARGUMENT, "The given binary array does not seem to contain" + " a whole StunMessage: given " - + ((int) arrayLen) + + arrayLen + " bytes of " + message.getName() + " but expecting " + (offset + TRANSACTION_ID_LENGTH + length)); } - byte tranID[] = new byte[TRANSACTION_ID_LENGTH]; + byte[] tranID = new byte[TRANSACTION_ID_LENGTH]; System.arraycopy(binMessage, offset, tranID, 0, TRANSACTION_ID_LENGTH); try { if(rfc3489Compat) { - byte rfc3489TranID[] = new byte[TRANSACTION_ID_LENGTH + 4]; + byte[] rfc3489TranID = new byte[TRANSACTION_ID_LENGTH + 4]; System.arraycopy(cookie, 0, rfc3489TranID, 0, 4); System.arraycopy(tranID, 0, rfc3489TranID, 4, TRANSACTION_ID_LENGTH); diff --git a/src/main/java/org/ice4j/stack/MessageProcessingTask.java b/src/main/java/org/ice4j/stack/MessageProcessingTask.java index 45d1bce..804aac3 100644 --- a/src/main/java/org/ice4j/stack/MessageProcessingTask.java +++ b/src/main/java/org/ice4j/stack/MessageProcessingTask.java @@ -177,8 +177,8 @@ class MessageProcessingTask { stunMessage = Message.decode(message.getBytes(), - (char) 0, - (char) message.getMessageLength()); + 0, + message.getMessageLength()); } catch (StunException ex) { diff --git a/src/main/kotlin/org/ice4j/ice/AgentConfig.kt b/src/main/kotlin/org/ice4j/ice/AgentConfig.kt index 0745cb7..762fbe1 100644 --- a/src/main/kotlin/org/ice4j/ice/AgentConfig.kt +++ b/src/main/kotlin/org/ice4j/ice/AgentConfig.kt @@ -18,7 +18,6 @@ package org.ice4j.ice import org.jitsi.metaconfig.config import java.time.Duration - import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource class AgentConfig { @@ -60,4 +59,4 @@ class AgentConfig { @JvmField val config = AgentConfig() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/org/ice4j/ice/harvest/HarvestConfig.kt b/src/main/kotlin/org/ice4j/ice/harvest/HarvestConfig.kt index a751484..1e6ff1a 100644 --- a/src/main/kotlin/org/ice4j/ice/harvest/HarvestConfig.kt +++ b/src/main/kotlin/org/ice4j/ice/harvest/HarvestConfig.kt @@ -19,7 +19,6 @@ package org.ice4j.ice.harvest import org.jitsi.metaconfig.config import org.jitsi.metaconfig.optionalconfig import java.time.Duration - import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource class HarvestConfig { @@ -64,8 +63,8 @@ class HarvestConfig { fun stunMappingCandidateHarvesterAddresses() = stunMappingCandidateHarvesterAddresses val enableAwsHarvester: Boolean by config { - "org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER".from(configSource).transformedBy { !it } - "ice4j.harvest.mapping.aws.enabled".from(configSource) + "org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER".from(configSource).transformedBy { !it } + "ice4j.harvest.mapping.aws.enabled".from(configSource) } fun enableAwsHarvester() = enableAwsHarvester @@ -79,4 +78,4 @@ class HarvestConfig { @JvmField val config = HarvestConfig() } -} \ No newline at end of file +} diff --git a/src/test/java/org/ice4j/MessageEventDispatchingTest.java b/src/test/java/org/ice4j/MessageEventDispatchingTest.java index 693df1b..056f79b 100644 --- a/src/test/java/org/ice4j/MessageEventDispatchingTest.java +++ b/src/test/java/org/ice4j/MessageEventDispatchingTest.java @@ -19,18 +19,18 @@ package org.ice4j; import java.util.*; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.message.*; import org.ice4j.socket.*; import org.ice4j.stack.*; - +import org.junit.jupiter.api.*; /** * Test event dispatching for both client and server. *` * @author Emil Ivov */ -public class MessageEventDispatchingTest extends TestCase +public class MessageEventDispatchingTest { /** * The stack that we are using for the tests. @@ -95,10 +95,9 @@ public class MessageEventDispatchingTest extends TestCase * * @throws Exception if anything goes wrong. */ - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); - stunStack = new StunStack(); clientSock = new IceUdpSocketWrapper( @@ -126,7 +125,8 @@ public class MessageEventDispatchingTest extends TestCase * * @throws Exception if anything goes wrong. */ - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { stunStack.removeSocket(clientAddress); stunStack.removeSocket(serverAddress); @@ -138,8 +138,6 @@ public class MessageEventDispatchingTest extends TestCase requestCollector = null; responseCollector = null; - - super.tearDown(); } /** @@ -147,6 +145,7 @@ public class MessageEventDispatchingTest extends TestCase * * @throws Exception upon a stun failure */ + @Test public void testClientTransactionTimeouts() throws Exception { String oldRetransValue = System.getProperty( @@ -156,13 +155,11 @@ public class MessageEventDispatchingTest extends TestCase responseCollector); responseCollector.waitForTimeout(); - assertEquals( - "No timeout was produced upon expiration of a client transaction", - responseCollector.receivedResponses.size(), 1); + assertEquals(1, responseCollector.receivedResponses.size(), + "No timeout was produced upon expiration of a client transaction"); - assertEquals( - "No timeout was produced upon expiration of a client transaction", - responseCollector.receivedResponses.get(0), "timeout"); + assertEquals("timeout", responseCollector.receivedResponses.get(0), + "No timeout was produced upon expiration of a client transaction"); //restore the retransmissions prop in case others are counting on //defaults. @@ -178,6 +175,7 @@ public class MessageEventDispatchingTest extends TestCase * * @throws java.lang.Exception upon any failure */ + @Test public void testEventDispatchingUponIncomingRequests() throws Exception { //prepare to listen @@ -189,8 +187,8 @@ public class MessageEventDispatchingTest extends TestCase requestCollector.waitForRequest(); //verify - assertTrue("No MessageEvents have been dispatched", - requestCollector.receivedRequests.size() == 1); + assertEquals(1, requestCollector.receivedRequests.size(), + "No MessageEvents have been dispatched"); } /** @@ -199,6 +197,7 @@ public class MessageEventDispatchingTest extends TestCase * * @throws java.lang.Exception upon any failure */ + @Test public void testSelectiveEventDispatchingUponIncomingRequests() throws Exception { @@ -216,19 +215,17 @@ public class MessageEventDispatchingTest extends TestCase requestCollector2.waitForRequest(); //verify - assertTrue( - "A MessageEvent was received by a non-interested selective listener", - requestCollector.receivedRequests.size() == 0); - assertTrue( - "No MessageEvents have been dispatched for a selective listener", - requestCollector2.receivedRequests.size() == 1); + assertEquals(0, requestCollector.receivedRequests.size(), + "A MessageEvent was received by a non-interested selective listener"); + assertEquals(1, requestCollector2.receivedRequests.size(), + "No MessageEvents have been dispatched for a selective listener"); } - /** * Makes sure that we receive response events. * @throws Exception if we screw up. */ + @Test public void testServerResponseRetransmissions() throws Exception { //prepare to listen @@ -249,15 +246,14 @@ public class MessageEventDispatchingTest extends TestCase responseCollector.waitForResponse(); //verify that we got the response. - assertTrue( - "There were no retransmissions of a binding response", - responseCollector.receivedResponses.size() == 1 ); + assertEquals(1, responseCollector.receivedResponses.size(), + "There were no retransmissions of a binding response"); } /** * A utility class we use to collect incoming requests. */ - private class PlainRequestCollector implements RequestListener + private static class PlainRequestCollector implements RequestListener { /** all requests we've received so far. */ public final Vector receivedRequests = new Vector<>(); diff --git a/src/test/java/org/ice4j/MsgFixture.java b/src/test/java/org/ice4j/MsgFixture.java index c2679b6..cc28691 100644 --- a/src/test/java/org/ice4j/MsgFixture.java +++ b/src/test/java/org/ice4j/MsgFixture.java @@ -243,20 +243,4 @@ public class MsgFixture 0x00, 0x20, 0x00, 0x21, 0x00, 0x22, 0x00, 0x22 }; - - - public MsgFixture() - { - - } - - public void setUp() - { - - } - - public void tearDown() - { - } - } diff --git a/src/test/java/org/ice4j/PseudoTcpTestSuite.java b/src/test/java/org/ice4j/PseudoTcpTestSuite.java deleted file mode 100644 index 0ce4eb3..0000000 --- a/src/test/java/org/ice4j/PseudoTcpTestSuite.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 Atlassian Pty Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.ice4j; - -import junit.framework.*; - -/** - * Contains pseudo TCP tests. - * - * @author Pawel Domas - */ -public class PseudoTcpTestSuite - extends TestCase -{ - - /** - * Creates a new instance of the suite - * - * @param s test name - */ - public PseudoTcpTestSuite(String s) - { - super(s); - } - - /** - * Returns the suite of tests to run. - * @return the suite of tests to run. - */ - public static Test suite() - { - TestSuite suite = new TestSuite(); - - // byte fifo buffer - suite.addTestSuite(org.ice4j.pseudotcp.util.ByteFifoBufferTest.class); - // transfer - suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpTestTransfer.class); - // ping pong - suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpTestPingPong.class); - // receive window - suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpTestRecvWindow.class); - // stream - suite.addTestSuite(org.ice4j.pseudotcp.PseudoTcpStreamTest.class); - - return suite; - } -} diff --git a/src/test/java/org/ice4j/StunTestSuite.java b/src/test/java/org/ice4j/StunTestSuite.java deleted file mode 100644 index 43be793..0000000 --- a/src/test/java/org/ice4j/StunTestSuite.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2015 Atlassian Pty Ltd - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.ice4j; - -import junit.framework.*; - -/** - * Contains all tests in the ice4j project. - * - * @author Emil Ivov - */ -public class StunTestSuite - extends TestCase -{ - - /** - * Creates a new instance of the suite - * - * @param s test name - */ - public StunTestSuite(String s) - { - super(s); - } - - /** - * Returns the suite of tests to run. - * @return the suite of tests to run. - */ - public static Test suite() - { - TestSuite suite = new TestSuite(); - - //attributes - suite.addTestSuite(org.ice4j.attribute. - AddressAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - XorOnlyTest.class); - suite.addTestSuite(org.ice4j.attribute. - AttributeDecoderTest.class); - suite.addTestSuite(org.ice4j.attribute. - ChangeRequestAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - ErrorCodeAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - UnknownAttributesAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - SoftwareAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - OptionalAttributeAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - ConnectionIdAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute. - RequestedAddressFamilyAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute.UsernameAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute.NonceAttributeTest.class); - suite.addTestSuite(org.ice4j.attribute.RealmAttributeTest.class); - - //messages - suite.addTestSuite(org.ice4j.message.MessageFactoryTest.class); - suite.addTestSuite(org.ice4j.message.MessageTest.class); - - //stack - suite.addTestSuite(org.ice4j.stack.ShallowStackTest.class); - - //event dispatching - suite.addTestSuite(org.ice4j.MessageEventDispatchingTest.class); - - //transactions - suite.addTestSuite(org.ice4j.TransactionSupportTests.class); - - //client - suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest.class); - suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest_v6.class); - suite.addTestSuite(org.ice4j.stunclient.StunAddressDiscovererTest_v4v6.class); - - return suite; - } -} diff --git a/src/test/java/org/ice4j/TransactionSupportTests.java b/src/test/java/org/ice4j/TransactionSupportTests.java index d47a7af..b952064 100644 --- a/src/test/java/org/ice4j/TransactionSupportTests.java +++ b/src/test/java/org/ice4j/TransactionSupportTests.java @@ -17,14 +17,15 @@ */ package org.ice4j; +import java.net.*; import java.util.*; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.message.*; import org.ice4j.socket.*; import org.ice4j.stack.*; - +import org.junit.jupiter.api.*; /** * Test how client and server behave, how they recognize/adopt messages and * how they both handle retransmissions (i.e. client transactions should make @@ -32,19 +33,17 @@ import org.ice4j.stack.*; * * @author Emil Ivov */ -public class TransactionSupportTests extends TestCase +public class TransactionSupportTests { /** * The client address we use for this test. */ - TransportAddress clientAddress - = new TransportAddress("127.0.0.1", 5216, Transport.UDP); + TransportAddress clientAddress; /** * The client address we use for this test. */ - TransportAddress serverAddress - = new TransportAddress("127.0.0.1", 5255, Transport.UDP); + TransportAddress serverAddress; /** * The socket the client uses in this test. @@ -86,15 +85,19 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if something goes bad. */ - protected void setUp() + @BeforeEach + public void setUp() throws Exception { - super.setUp(); - clientSock = new IceUdpSocketWrapper( - new SafeCloseDatagramSocket(clientAddress)); + new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0))); serverSock = new IceUdpSocketWrapper( - new SafeCloseDatagramSocket(serverAddress)); + new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0))); + + clientAddress + = new TransportAddress("127.0.0.1", clientSock.getLocalPort(), Transport.UDP); + serverAddress + = new TransportAddress("127.0.0.1", serverSock.getLocalPort(), Transport.UDP); stunStack = new StunStack(); stunStack.addSocket(clientSock); @@ -129,7 +132,8 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if something does not go as planned. */ - protected void tearDown() + @AfterEach + public void tearDown() throws Exception { stunStack.removeSocket(clientAddress); @@ -156,8 +160,6 @@ public class TransactionSupportTests extends TestCase System.setProperty( StackProperties.FIRST_CTRAN_RETRANS_AFTER, ""); - - super.tearDown(); } /** @@ -165,6 +167,7 @@ public class TransactionSupportTests extends TestCase * * @throws java.lang.Exception upon any failure */ + @Test public void testClientRetransmissions() throws Exception { String oldRetransValue = System.getProperty( @@ -195,11 +198,10 @@ public class TransactionSupportTests extends TestCase = requestCollector.getRequestsForTransaction( bindingRequest.getTransactionID()); - assertTrue("No retransmissions of the request have been received", - reqs.size() > 1); - assertTrue("The binding request has been retransmitted more than it " - +"should have!", - reqs.size() >= 3); + assertTrue(reqs.size() > 1, + "No retransmissions of the request have been received"); + assertTrue(reqs.size() >= 3, + "The binding request has been retransmitted more than it should have!"); //restore the retransmissions prop in case others are counting on //defaults. @@ -222,6 +224,7 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if anything goes wrong. */ + @Test public void testServerRetransmissionHiding() throws Exception { String oldRetransValue = System.getProperty( @@ -244,9 +247,8 @@ public class TransactionSupportTests extends TestCase = requestCollector.getRequestsForTransaction( bindingRequest.getTransactionID()); - assertTrue( - "Retransmissions of a binding request were propagated " - + "to the server", reqs.size() <= 1 ); + assertTrue(reqs.size() <= 1, + "Retransmissions of a binding request were propagated to the server"); //restore the retransmissions prop in case others are counting on //defaults. @@ -264,6 +266,7 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if we screw up. */ + @Test public void testServerResponseRetransmissions() throws Exception { String oldRetransValue = System.getProperty( @@ -303,10 +306,9 @@ public class TransactionSupportTests extends TestCase Thread.sleep(500); //verify that we received a fair number of retransmitted responses. - assertTrue( + assertTrue(responseCollector.receivedResponses.size() < 3, "There were too few retransmissions of a binding response: " - +responseCollector.receivedResponses.size(), - responseCollector.receivedResponses.size() < 3 ); + +responseCollector.receivedResponses.size()); //restore the retransmissions prop in case others are counting on //defaults. @@ -323,6 +325,7 @@ public class TransactionSupportTests extends TestCase * A (very) weak test, verifying that transaction IDs are unique. * @throws Exception in case we feel like it. */ + @Test public void testUniqueIDs() throws Exception { stunStack.addRequestListener(serverAddress, requestCollector); @@ -366,10 +369,11 @@ public class TransactionSupportTests extends TestCase StunMessageEvent evt2 = reqs2.get(0); - assertFalse( - "Consecutive requests were assigned the same transaction id", - Arrays.equals( evt1.getMessage().getTransactionID(), - evt2.getMessage().getTransactionID())); + assertFalse(Arrays.equals( + evt1.getMessage().getTransactionID(), + evt2.getMessage().getTransactionID()), + "Consecutive requests were assigned the same transaction id" + ); } /** @@ -378,6 +382,7 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if the gods so decide. */ + @Test public void testClientTransactionMaxRetransmisssionsConfigurationParameter() throws Exception { @@ -404,13 +409,10 @@ public class TransactionSupportTests extends TestCase = requestCollector.getRequestsForTransaction( bindingRequest.getTransactionID()); - assertTrue("No retransmissions of the request have been received", - reqs.size() > 1); - assertEquals( - "The MAX_RETRANSMISSIONS param was not taken into account!", - reqs.size(), - 3); - + assertTrue(reqs.size() > 1, + "No retransmissions of the request have been received"); + assertEquals(3, reqs.size(), + "The MAX_RETRANSMISSIONS param was not taken into account!"); } /** @@ -419,6 +421,7 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if we are having a bad day. */ + @Test public void testMinWaitIntervalConfigurationParameter() throws Exception { @@ -442,8 +445,8 @@ public class TransactionSupportTests extends TestCase //verify Vector reqs = requestCollector.getRequestsForTransaction( bindingRequest.getTransactionID()); - assertTrue("A retransmissions of the request was sent too early", - reqs.size() < 2); + assertTrue(reqs.size() < 2, + "A retransmissions of the request was sent too early"); //wait for a send Thread.sleep(110); @@ -452,8 +455,8 @@ public class TransactionSupportTests extends TestCase bindingRequest.getTransactionID()); //verify - assertEquals("A retransmissions of the request was not sent", - 2, reqs.size()); + assertEquals(2, reqs.size(), + "A retransmissions of the request was not sent"); } /** @@ -462,6 +465,7 @@ public class TransactionSupportTests extends TestCase * * @throws Exception if the gods so decide. */ + @Test public void testMaxWaitIntervalConfigurationParameter() throws Exception { @@ -488,10 +492,8 @@ public class TransactionSupportTests extends TestCase Vector reqs = requestCollector.getRequestsForTransaction( bindingRequest.getTransactionID()); - assertEquals("Not all retransmissions were made for the expected period " - +"of time", - 12, - reqs.size()); + assertEquals(12, reqs.size(), + "Not all retransmissions were made for the expected period of time"); //wait for a send Thread.sleep(1800); @@ -499,22 +501,20 @@ public class TransactionSupportTests extends TestCase //verify reqs = requestCollector.getRequestsForTransaction( bindingRequest.getTransactionID()); - assertEquals("A retransmissions of the request was sent, while not " - +"supposed to", - 12, - reqs.size()); + assertEquals(12, reqs.size(), + "A retransmissions of the request was sent, while not supposed to"); } /** * A simply utility for asynchronous collection of requests. */ - private class PlainRequestCollector + private static class PlainRequestCollector implements RequestListener { /** * */ - private Vector receivedRequestsVector + private final Vector receivedRequestsVector = new Vector<>(); /** diff --git a/src/test/java/org/ice4j/attribute/AddressAttributeTest.java b/src/test/java/org/ice4j/attribute/AddressAttributeTest.java index ade60d3..0e720dd 100644 --- a/src/test/java/org/ice4j/attribute/AddressAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/AddressAttributeTest.java @@ -17,46 +17,40 @@ */ package org.ice4j.attribute; -import java.util.*; - -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * * @author Emil Ivov */ -public class AddressAttributeTest extends TestCase { +public class AddressAttributeTest +{ private AddressAttribute addressAttribute = null; private MsgFixture msgFixture; - public AddressAttributeTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); - + @BeforeEach + public void setUp() throws Exception + { addressAttribute = new MappedAddressAttribute(); msgFixture = new MsgFixture(); - - msgFixture.setUp(); } - protected void tearDown() throws Exception { + @AfterEach + public void tearDown() throws Exception + { addressAttribute = null; - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } /** * Verify that AddressAttribute descendants have correctly set types and * names. */ - public void testAddressAttributeDescendants() { + @Test + public void testAddressAttributeDescendants() + { char expectedType; char actualType; String expectedName; @@ -71,10 +65,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "MAPPED-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("MappedAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("MappedAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "MappedAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "MappedAddressAttribute does not the right name."); //SOURCE-ADDRESS @@ -86,10 +80,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "SOURCE-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("SourceAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("SourceAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "SourceAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "SourceAddressAttribute does not the right name."); //CHANGED-ADDRESS @@ -101,10 +95,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "CHANGED-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("ChangedAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("ChangedAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "ChangedAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "ChangedAddressAttribute does not the right name."); //RESPONSE-ADDRESS @@ -116,10 +110,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "RESPONSE-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("ResponseAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("ResponseAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "ResponseAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "ResponseAddressAttribute does not the right name."); //REFLECTED-FROM @@ -131,10 +125,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "REFLECTED-FROM"; actualName = addressAttribute.getName(); - assertEquals("ReflectedFromAttribute does not the right type.", - expectedType, actualType); - assertEquals("ReflectedFromAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "ReflectedFromAttribute does not the right type."); + assertEquals(expectedName, actualName, + "ReflectedFromAttribute does not the right name."); //REFLECTED-FROM addressAttribute = new ReflectedFromAttribute(); @@ -145,10 +139,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "REFLECTED-FROM"; actualName = addressAttribute.getName(); - assertEquals("ReflectedFromAttribute does not the right type.", - expectedType, actualType); - assertEquals("ReflectedFromAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "ReflectedFromAttribute does not the right type."); + assertEquals(expectedName, actualName, + "ReflectedFromAttribute does not the right name."); //XOR-MAPPED-ADDRESS addressAttribute = new XorMappedAddressAttribute(); @@ -159,10 +153,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "XOR-MAPPED-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("XorMappedAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("XorMappedAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "XorMappedAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "XorMappedAddressAttribute does not the right name."); /* ALTERNATE-SERVER */ addressAttribute = new AlternateServerAttribute(); @@ -173,10 +167,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "ALTERNATE-SERVER"; actualName = addressAttribute.getName(); - assertEquals("AlternateServerAttribute does not the right type.", - expectedType, actualType); - assertEquals("AlternateAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "AlternateServerAttribute does not the right type."); + assertEquals(expectedName, actualName, + "AlternateAttribute does not the right name."); /* XOR-PEER-ADDRESS */ @@ -188,10 +182,10 @@ public class AddressAttributeTest extends TestCase { expectedName = "XOR-PEER-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("XorPeerAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("XorPeerAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "XorPeerAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "XorPeerAddressAttribute does not the right name."); /* XOR-RELAYED-ADDRESS */ addressAttribute = new XorRelayedAddressAttribute(); @@ -202,15 +196,16 @@ public class AddressAttributeTest extends TestCase { expectedName = "XOR-RELAYED-ADDRESS"; actualName = addressAttribute.getName(); - assertEquals("XorRelayedAddressAttribute does not the right type.", - expectedType, actualType); - assertEquals("XorRelayedAddressAttribute does not the right name.", - expectedName, actualName); + assertEquals(expectedType, actualType, + "XorRelayedAddressAttribute does not the right type."); + assertEquals(expectedName, actualName, + "XorRelayedAddressAttribute does not the right name."); } /** * Verifies that xorred address-es are properly xor-ed for IPv4 addresses. */ + @Test public void testXorMappedAddressXoring_v4() { XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute(); @@ -223,11 +218,12 @@ public class AddressAttributeTest extends TestCase { TransportAddress xorredAddr = addressAttribute.applyXor( new byte[]{(byte)130,79,95,53,0,0,0,0,0,0,0,0,0,0,0,0,0}); - assertTrue("Xorring the address with itself didn't return 00000...", - Arrays.equals(xorredAddr.getAddressBytes(), new byte[]{0,0,0,0})); + assertArrayEquals( + xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0 }, + "Xorring the address with itself didn't return 00000..."); - assertTrue("Port was not xorred", - testAddress.getPort() != xorredAddr.getPort()); + assertNotEquals(xorredAddr.getPort(), testAddress.getPort(), + "Port was not xorred"); //Test xor-ing the original with the xored - should get the xor code addressAttribute.setAddress(testAddress); @@ -237,13 +233,11 @@ public class AddressAttributeTest extends TestCase { xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes()); - assertTrue("Xorring the original with the xor-ed didn't " - +"return the code..", - Arrays.equals( xorredAddr.getAddressBytes(), - new byte[]{21,22,23,24})); + assertArrayEquals( + xorredAddr.getAddressBytes(), new byte[] { 21, 22, 23, 24 }, + "Xorring the original with the xor-ed didn't return the code."); - assertTrue("Port was not xorred", - testAddress.getPort() != 0xFFFF); + assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred"); //Test double xor-ing - should get the original addressAttribute.setAddress(testAddress); @@ -254,13 +248,14 @@ public class AddressAttributeTest extends TestCase { xorredAddr = addressAttribute.applyXor( new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}); - assertEquals("Double xorring didn't give the original ...", - testAddress, xorredAddr); + assertEquals(testAddress, xorredAddr, + "Double xorring didn't give the original"); } /** * Verifies that xorred address-es are properly xor-ed for IPv6 addresses. */ + @Test public void testXorMappedAddressXoring_v6() { XorMappedAddressAttribute addressAttribute @@ -278,15 +273,15 @@ public class AddressAttributeTest extends TestCase { (byte)0x02, (byte)0x02, (byte)0x8a, (byte)0xff, (byte)0xfe, (byte)0xbe, (byte)0x13, (byte)0x0b}); - assertTrue("Xorring the address with itself didn't return 00000...", - Arrays.equals(xorredAddr.getAddressBytes(), - new byte[]{0,0,0,0, - 0,0,0,0, - 0,0,0,0, - 0,0,0,0})); + assertArrayEquals( + xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0 }, + "Xorring the address with itself didn't return 00000..."); - assertTrue("Port was not xorred", - testAddress.getPort() != xorredAddr.getPort()); + assertNotEquals(testAddress.getPort(), xorredAddr.getPort(), + "Port was not xorred"); //Test xor-ing the original with the xored - should get the xor code addressAttribute.setAddress(testAddress); @@ -295,13 +290,13 @@ public class AddressAttributeTest extends TestCase { xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes()); - assertTrue("Xorring the original with the xor-ed didn't return the code..", - Arrays.equals( - xorredAddr.getAddressBytes(), - new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36})); - - assertTrue("Port was not xorred", - testAddress.getPort() != 0xFFFF); + assertArrayEquals( + xorredAddr.getAddressBytes(), + new byte[] { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 36 }, + "Xorring the original with the xor-ed didn't return the code."); + + assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred"); //Test double xor-ing - should get the original addressAttribute.setAddress(testAddress); @@ -312,8 +307,8 @@ public class AddressAttributeTest extends TestCase { xorredAddr = addressAttribute.applyXor( new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}); - assertEquals("Double xorring didn't give the original ...", - testAddress, xorredAddr); + assertEquals(testAddress, xorredAddr, + "Double xorring didn't give the original"); } /** @@ -321,6 +316,7 @@ public class AddressAttributeTest extends TestCase { * * @throws StunException if something goes wrong */ + @Test public void testDecodeAttributeBody() throws StunException { byte[] attributeValue = msgFixture.mappedAddress; char offset = Attribute.HEADER_LENGTH; @@ -330,12 +326,12 @@ public class AddressAttributeTest extends TestCase { assertEquals( - "AddressAttribute.decode() did not properly decode the port field.", - MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort()); - assertTrue( - "AddressAttribute.decode() did not properly decode the address field.", - Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, - addressAttribute.getAddressBytes())); + MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort(), + "AddressAttribute.decode() did not properly decode the port field."); + assertArrayEquals( + MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, + addressAttribute.getAddressBytes(), + "AddressAttribute.decode() did not properly decode the address field."); } @@ -344,6 +340,7 @@ public class AddressAttributeTest extends TestCase { * Test whetner sample binary arrays are correctly decoded. * @throws StunException if something goes wrong */ + @Test public void testDecodeAttributeBodyv6() throws StunException { byte[] attributeValue = msgFixture.mappedAddressv6; char offset = Attribute.HEADER_LENGTH; @@ -352,14 +349,13 @@ public class AddressAttributeTest extends TestCase { addressAttribute.decodeAttributeBody(attributeValue, offset, length); - assertEquals("decode() failed for an IPv6 Addr's port.", - MsgFixture.ADDRESS_ATTRIBUTE_PORT, - addressAttribute.getPort()); - assertTrue("AddressAttribute.decode() failed for an IPv6 address.", - Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6, - addressAttribute.getAddressBytes())); - - + assertEquals(MsgFixture.ADDRESS_ATTRIBUTE_PORT, + addressAttribute.getPort(), + "decode() failed for an IPv6 Addr's port."); + assertArrayEquals( + MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6, + addressAttribute.getAddressBytes(), + "AddressAttribute.decode() failed for an IPv6 address."); } /** @@ -367,6 +363,7 @@ public class AddressAttributeTest extends TestCase { * * @throws Exception java.lang.Exception if we fail */ + @Test public void testEncode() throws Exception { @@ -378,9 +375,8 @@ public class AddressAttributeTest extends TestCase { Transport.UDP)); byte[] actualReturn = addressAttribute.encode(); - assertTrue("AddressAttribute.encode() did not " - +"properly encode a sample attribute", - Arrays.equals( expectedReturn, actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "AddressAttribute.encode() did not properly encode a sample attribute"); } /** @@ -388,6 +384,7 @@ public class AddressAttributeTest extends TestCase { * * @throws Exception java.lang.Exception if we fail */ + @Test public void testEncodev6() throws Exception { @@ -398,8 +395,8 @@ public class AddressAttributeTest extends TestCase { MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); byte[] actualReturn = addressAttribute.encode(); - assertTrue("An AddressAttribute did not properly encode an IPv6 addr.", - Arrays.equals( expectedReturn, actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "An AddressAttribute did not properly encode an IPv6 addr."); } @@ -409,6 +406,7 @@ public class AddressAttributeTest extends TestCase { * * @throws Exception java.lang.Exception if we fail */ + @Test public void testEquals() throws Exception { @@ -417,8 +415,8 @@ public class AddressAttributeTest extends TestCase { boolean expectedReturn = false; boolean actualReturn = addressAttribute.equals(target); - assertEquals("AddressAttribute.equals() failed against a null target.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "AddressAttribute.equals() failed against a null target."); //difference test target = new MappedAddressAttribute(); @@ -434,9 +432,8 @@ public class AddressAttributeTest extends TestCase { expectedReturn = false; actualReturn = addressAttribute.equals(target); - assertEquals( - "AddressAttribute.equals() failed against a different target.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "AddressAttribute.equals() failed against a different target."); //equality test target.setAddress( new TransportAddress( @@ -445,9 +442,8 @@ public class AddressAttributeTest extends TestCase { expectedReturn = true; actualReturn = addressAttribute.equals(target); - assertEquals( - "AddressAttribute.equals() failed against an equal target.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "AddressAttribute.equals() failed against an equal target."); //ipv6 equality test target.setAddress( new TransportAddress( @@ -461,8 +457,8 @@ public class AddressAttributeTest extends TestCase { expectedReturn = true; actualReturn = addressAttribute.equals(target); - assertEquals("AddressAttribute.equals() failed for IPv6 addresses.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "AddressAttribute.equals() failed for IPv6 addresses."); } /** @@ -470,6 +466,7 @@ public class AddressAttributeTest extends TestCase { * * @throws Exception java.lang.Exception if we fail */ + @Test public void testGetDataLength() throws Exception { @@ -482,8 +479,8 @@ public class AddressAttributeTest extends TestCase { char actualReturn = addressAttribute.getDataLength(); - assertEquals("Datalength is not propoerly calculated", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "Datalength is not propoerly calculated"); expectedReturn = 20;//1-padding + 1-family + 2-port + 16-address addressAttribute.setAddress( new TransportAddress( @@ -492,8 +489,8 @@ public class AddressAttributeTest extends TestCase { actualReturn = addressAttribute.getDataLength(); - assertEquals("Datalength is not propoerly calculated", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "Datalength is not propoerly calculated"); } /** @@ -501,6 +498,7 @@ public class AddressAttributeTest extends TestCase { * * @throws Exception java.lang.Exception if we fail */ + @Test public void testGetFamily() throws Exception { @@ -509,8 +507,8 @@ public class AddressAttributeTest extends TestCase { MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); byte actualReturn = addressAttribute.getFamily(); - assertEquals("Address family was not 1 for an IPv4", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "Address family was not 1 for an IPv4"); //ipv6 expectedReturn = 2; @@ -518,9 +516,7 @@ public class AddressAttributeTest extends TestCase { MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6, MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); actualReturn = addressAttribute.getFamily(); - assertEquals("Address family was not 2 for an IPv6 address", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "Address family was not 2 for an IPv6 address"); } - } diff --git a/src/test/java/org/ice4j/attribute/AttributeDecoderTest.java b/src/test/java/org/ice4j/attribute/AttributeDecoderTest.java index 1a9f288..e72e4b2 100644 --- a/src/test/java/org/ice4j/attribute/AttributeDecoderTest.java +++ b/src/test/java/org/ice4j/attribute/AttributeDecoderTest.java @@ -17,28 +17,23 @@ */ package org.ice4j.attribute; + import org.ice4j.*; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; /** * We have already tested individual decode methods, so our job here * is to verify that that AttributeDecoder.decode distributes the right way. */ -public class AttributeDecoderTest extends TestCase -{ +public class AttributeDecoderTest { private MsgFixture msgFixture; private byte[] expectedAttributeValue = null; - public AttributeDecoderTest(String name) + @BeforeEach + public void setUp() throws Exception { - super(name); - } - - protected void setUp() throws Exception - { - super.setUp(); - msgFixture = new MsgFixture(); //init a sample body @@ -48,18 +43,15 @@ public class AttributeDecoderTest extends TestCase System.arraycopy(msgFixture.unknownOptionalAttribute, offset, expectedAttributeValue, 0, expectedAttributeValue.length); - - msgFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } + @Test public void testDecodeMappedAddress() throws Exception { @@ -79,11 +71,11 @@ public class AttributeDecoderTest extends TestCase Attribute actualReturn = AttributeDecoder.decode( bytes, offset, length); - assertEquals( - "AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute"); } + @Test public void testDecodeMappedAddress_v6() throws Exception { @@ -104,10 +96,12 @@ public class AttributeDecoderTest extends TestCase bytes, offset, length); assertEquals( - "AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute", - expectedReturn, actualReturn); + expectedReturn, actualReturn, + "AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute" + ); } + @Test public void testDecodeChangeRequest() throws Exception { @@ -123,12 +117,13 @@ public class AttributeDecoderTest extends TestCase Attribute actualReturn = AttributeDecoder.decode( bytes, offset, length); - assertEquals("AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute" + ); } - public void testDecodeErrorCode() + @Test + public void testDecodeErrorCode() throws Exception { // @@ -144,13 +139,12 @@ public class AttributeDecoderTest extends TestCase Attribute actualReturn = AttributeDecoder.decode( bytes, offset, length); - assertEquals( - "AttributeDecoder.decode() failed for a ERROR-CODE attribute", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "AttributeDecoder.decode() failed for a ERROR-CODE attribute"); } - public void testDecodeUnknownAttributes() + @Test + public void testDecodeUnknownAttributes() throws Exception { //unknown attributes @@ -168,13 +162,12 @@ public class AttributeDecoderTest extends TestCase Attribute actualReturn = AttributeDecoder.decode( bytes, offset, length); - assertEquals( - "AttributeDecoder.decode() failed for a ERROR-CODE attribute", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "AttributeDecoder.decode() failed for a ERROR-CODE attribute"); } - public void testDecodeUnknownOptionalAttribute() + @Test + public void testDecodeUnknownOptionalAttribute() throws Exception { //unknown attributes @@ -190,9 +183,8 @@ public class AttributeDecoderTest extends TestCase Attribute actualReturn = AttributeDecoder.decode( bytes, offset, length); - assertEquals( - "AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute"); } } diff --git a/src/test/java/org/ice4j/attribute/ChangeRequestAttributeTest.java b/src/test/java/org/ice4j/attribute/ChangeRequestAttributeTest.java index f2eb500..c9d0a1a 100644 --- a/src/test/java/org/ice4j/attribute/ChangeRequestAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/ChangeRequestAttributeTest.java @@ -17,57 +17,47 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Tests the CHANGE-REQUEST attribute class. * * @author Emil Ivov */ -public class ChangeRequestAttributeTest extends TestCase +public class ChangeRequestAttributeTest { private ChangeRequestAttribute changeRequestAttribute = null; private MsgFixture binMessagesFixture; - public ChangeRequestAttributeTest(String name) + @BeforeEach + public void setUp() throws Exception { - super(name); - } - - protected void setUp() throws Exception - { - super.setUp(); changeRequestAttribute = new ChangeRequestAttribute(); binMessagesFixture = new MsgFixture(); - - binMessagesFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { changeRequestAttribute = null; - binMessagesFixture.tearDown(); - binMessagesFixture = null; - super.tearDown(); } /** * Test whether the constructed object has the proper type. */ + @Test public void testChangeRequestAttribute() { changeRequestAttribute = new ChangeRequestAttribute(); assertEquals( - "ChangeRequestAttribute did not construct an attribute with the " - +"correct type.", changeRequestAttribute.getAttributeType(), - Attribute.CHANGE_REQUEST); + Attribute.CHANGE_REQUEST, + "ChangeRequestAttribute did not construct an attribute with the correct type." + ); } @@ -76,6 +66,7 @@ public class ChangeRequestAttributeTest extends TestCase * * @throws StunException java.lang.Exception if we fail */ + @Test public void testDecodeAttributeBody() throws StunException { @@ -84,27 +75,31 @@ public class ChangeRequestAttributeTest extends TestCase char length = (char)(attributeValue.length - offset); changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length); - assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag", - MsgFixture.CHANGE_IP_FLAG_1, - changeRequestAttribute.getChangeIpFlag() - ); - assertEquals("decodeAttributeBody() did not properly decode the changePortFlag", - MsgFixture.CHANGE_PORT_FLAG_1, - changeRequestAttribute.getChangePortFlag() - ); + assertEquals( + MsgFixture.CHANGE_IP_FLAG_1, + changeRequestAttribute.getChangeIpFlag(), + "decodeAttributeBody() did not properly decode the changeIpFlag" + ); + assertEquals( + MsgFixture.CHANGE_PORT_FLAG_1, + changeRequestAttribute.getChangePortFlag(), + "decodeAttributeBody() did not properly decode the changePortFlag" + ); //2nd sample attributeValue = binMessagesFixture.chngReqTestValue2; - changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length); - assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag", - MsgFixture.CHANGE_IP_FLAG_2, - changeRequestAttribute.getChangeIpFlag() - ); - assertEquals("decodeAttributeBody() did not properly decode the changePortFlag", - MsgFixture.CHANGE_PORT_FLAG_2, - changeRequestAttribute.getChangePortFlag() - ); - + changeRequestAttribute + .decodeAttributeBody(attributeValue, offset, length); + assertEquals( + MsgFixture.CHANGE_IP_FLAG_2, + changeRequestAttribute.getChangeIpFlag(), + "decodeAttributeBody() did not properly decode the changeIpFlag" + ); + assertEquals( + MsgFixture.CHANGE_PORT_FLAG_2, + changeRequestAttribute.getChangePortFlag(), + "decodeAttributeBody() did not properly decode the changePortFlag" + ); changeRequestAttribute.getChangePortFlag(); } @@ -112,6 +107,7 @@ public class ChangeRequestAttributeTest extends TestCase /** * Create sample objects and test whether they encode properly. */ + @Test public void testEncode() { byte[] expectedReturn = binMessagesFixture.chngReqTestValue1; @@ -122,8 +118,8 @@ public class ChangeRequestAttributeTest extends TestCase changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1); byte[] actualReturn = changeRequestAttribute.encode(); - assertTrue("Object did not encode properly.", - Arrays.equals(expectedReturn, actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "Object did not encode properly."); //2nd test expectedReturn = binMessagesFixture.chngReqTestValue2; @@ -133,27 +129,22 @@ public class ChangeRequestAttributeTest extends TestCase changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2); actualReturn = changeRequestAttribute.encode(); - assertTrue("Object did not encode properly.", - Arrays.equals(expectedReturn, actualReturn)); - - + assertArrayEquals(expectedReturn, actualReturn, + "Object did not encode properly."); } /** * Tests the equals method against a null, a different and an identical * object. */ + @Test public void testEquals() { - ChangeRequestAttribute target = null; - boolean expectedReturn = false; - //null test - boolean actualReturn = changeRequestAttribute.equals(target); - assertEquals("Null value test failed", expectedReturn, actualReturn); + assertNotEquals(changeRequestAttribute, null); //test against a different object. - target = new ChangeRequestAttribute(); + ChangeRequestAttribute target = new ChangeRequestAttribute(); changeRequestAttribute.setChangeIpFlag(true); changeRequestAttribute.setChangePortFlag(false); @@ -161,9 +152,7 @@ public class ChangeRequestAttributeTest extends TestCase target.setChangeIpFlag(false); target.setChangePortFlag(true); - actualReturn = changeRequestAttribute.equals(target); - assertEquals("Test against a different value failed", - expectedReturn, actualReturn); + assertNotEquals(changeRequestAttribute, target); //test against an equal value target = new ChangeRequestAttribute(); @@ -173,33 +162,27 @@ public class ChangeRequestAttributeTest extends TestCase target.setChangeIpFlag(true); target.setChangePortFlag(false); - - expectedReturn = true; - actualReturn = changeRequestAttribute.equals(target); - assertEquals("Test against an equals value failed", - expectedReturn, actualReturn); - - + assertEquals(changeRequestAttribute, target); } + /** * Test whether the returned value is always 4. */ + @Test public void testGetDataLength() { char expectedReturn = 4; // constant 4 bytes of data char actualReturn = changeRequestAttribute.getDataLength(); - assertEquals("data length returned an invalid value", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "data length returned an invalid value"); } /** * Test whether we get a relevant name. */ + @Test public void testGetName() { - String expectedReturn = "CHANGE-REQUEST"; - String actualReturn = changeRequestAttribute.getName(); - assertEquals("Invalid name", expectedReturn, actualReturn); + assertEquals("CHANGE-REQUEST", changeRequestAttribute.getName()); } - } diff --git a/src/test/java/org/ice4j/attribute/ConnectionIdAttributeTest.java b/src/test/java/org/ice4j/attribute/ConnectionIdAttributeTest.java index fb47c7a..8b09502 100644 --- a/src/test/java/org/ice4j/attribute/ConnectionIdAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/ConnectionIdAttributeTest.java @@ -19,10 +19,9 @@ package org.ice4j.attribute; import org.ice4j.*; -import java.util.*; - -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.*; /** * Class to test the ConnectionIdAttribute class. * @@ -30,108 +29,86 @@ import junit.framework.*; * */ public class ConnectionIdAttributeTest - extends TestCase { private ConnectionIdAttribute connectionIdAttribute = null; private MsgFixture msgFixture; - @Override - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); this.connectionIdAttribute = new ConnectionIdAttribute(); this.msgFixture = new MsgFixture(); - - msgFixture.setUp(); } - @Override - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { this.connectionIdAttribute = null; - this.msgFixture.tearDown(); - this.msgFixture = null; - super.tearDown(); } /** * Tests whether data length is properly calculated. */ + @Test public void testGetDataLength() { char expectedReturn = 4; this.connectionIdAttribute .setConnectionIdValue(MsgFixture.CONNECTION_ID); char actualReturn = this.connectionIdAttribute.getDataLength(); - assertEquals( - "Datalength is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "Datalength is not properly calculated"); } /** * Tests getting the name. */ + @Test public void testGetName() { - String expectedReturn = "CONNECTION-ID"; - String actualReturn = connectionIdAttribute.getName(); - assertEquals( - "getting name failed", expectedReturn, actualReturn); + assertEquals("CONNECTION-ID", connectionIdAttribute.getName()); } /** * Tests the equals method against a null, a different and an identical * object. */ + @Test public void testEqualsObject() { // null test - ConnectionIdAttribute target = null; - boolean expectedReturn = false; - boolean actualReturn = connectionIdAttribute.equals(target); - - assertEquals( - "ConnectionIdAttribute.equals() failed against a null target.", - expectedReturn, actualReturn); + assertNotEquals(connectionIdAttribute, null); // difference test - target = new ConnectionIdAttribute(); + ConnectionIdAttribute target = new ConnectionIdAttribute(); int connectionId = MsgFixture.CONNECTION_ID_2; target.setConnectionIdValue(connectionId); connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID); - expectedReturn = false; - actualReturn = connectionIdAttribute.equals(target); - assertEquals( - "ConnectionIdAttribute.equals() failed against a different target.", - expectedReturn, actualReturn); + assertNotEquals(connectionIdAttribute, target, + "ConnectionIdAttribute.equals() failed against a different target."); // equality test target.setConnectionIdValue(MsgFixture.CONNECTION_ID); - - expectedReturn = true; - actualReturn = connectionIdAttribute.equals(target); - assertEquals( - "ConnectionIdAttribute.equals() failed against an equal target.", - expectedReturn, actualReturn); + assertEquals(connectionIdAttribute, target, + "ConnectionIdAttribute.equals() failed against an equal target."); } /** * Test whether attributes are properly encoded. */ + @Test public void testEncode() { byte[] expectedReturn = msgFixture.connectionId; connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID); byte[] actualReturn = connectionIdAttribute.encode(); - assertTrue( - "ConnectionIdAttribute.encode() did not " - + "properly encode a sample attribute", Arrays.equals( - expectedReturn, actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "ConnectionIdAttribute.encode() did not properly encode a sample attribute"); } /** @@ -140,6 +117,7 @@ public class ConnectionIdAttributeTest * @throws StunException if something goes wrong while decoding * Attribute Body. */ + @Test public void testDecodeAttributeBody() throws StunException { byte[] attributeValue = msgFixture.connectionId; @@ -150,31 +128,31 @@ public class ConnectionIdAttributeTest attributeValue, offset, length); assertEquals( - "ConnectionIdAttribute.decode() did not properly decode the " - + "connection id field.", MsgFixture.CONNECTION_ID, - connectionIdAttribute.getConnectionIdValue()); + MsgFixture.CONNECTION_ID, + connectionIdAttribute.getConnectionIdValue(), + "ConnectionIdAttribute.decode() did not properly decode the connection id field." + ); } /** * Tests that the connection Id is always integer. */ + @Test public void testGetConnectionIdValue() { int expectedReturn = 0x5555; this.connectionIdAttribute .setConnectionIdValue(MsgFixture.CONNECTION_ID); int actualReturn = this.connectionIdAttribute.getConnectionIdValue(); - assertEquals( - "ConnectionId is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "ConnectionId is not properly calculated"); expectedReturn = 0x2222; this.connectionIdAttribute .setConnectionIdValue(MsgFixture.CONNECTION_ID_2); actualReturn = this.connectionIdAttribute.getConnectionIdValue(); - assertEquals( - "ConnectionId is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "ConnectionId is not properly calculated"); } } diff --git a/src/test/java/org/ice4j/attribute/ErrorCodeAttributeTest.java b/src/test/java/org/ice4j/attribute/ErrorCodeAttributeTest.java index 081e424..5d7f87c 100644 --- a/src/test/java/org/ice4j/attribute/ErrorCodeAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/ErrorCodeAttributeTest.java @@ -17,51 +17,44 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * * @author Emil Ivov */ -public class ErrorCodeAttributeTest extends TestCase { +public class ErrorCodeAttributeTest +{ private ErrorCodeAttribute errorCodeAttribute = null; private MsgFixture msgFixture; - public ErrorCodeAttributeTest(String name) { - super(name); - } - - protected void setUp() throws Exception { - super.setUp(); + @BeforeEach + public void setUp() throws Exception + { errorCodeAttribute = new ErrorCodeAttribute(); msgFixture = new MsgFixture(); - - msgFixture.setUp(); } - protected void tearDown() throws Exception { + @AfterEach + public void tearDown() throws Exception { errorCodeAttribute = null; - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } /** * Test Attribute type */ + @Test public void testErrorCodeAttribute() { - errorCodeAttribute = new ErrorCodeAttribute(); - - assertEquals("ErrorCodeAttribute() constructed an attribute with an invalid type", - Attribute.ERROR_CODE, - errorCodeAttribute.getAttributeType()); + assertEquals( + Attribute.ERROR_CODE, + errorCodeAttribute.getAttributeType(), + "ErrorCodeAttribute() constructed an attribute with an invalid type" + ); } /** @@ -69,6 +62,7 @@ public class ErrorCodeAttributeTest extends TestCase { * * @throws StunException java.lang.Exception if we fail */ + @Test public void testDecodeAttributeBody() throws StunException { byte[] attributeValue = msgFixture.errCodeTestValue; @@ -76,18 +70,22 @@ public class ErrorCodeAttributeTest extends TestCase { char length = (char)(attributeValue.length - Attribute.HEADER_LENGTH); errorCodeAttribute.decodeAttributeBody(attributeValue, offset, length); - assertEquals("Error Class was not correctly decoded", - MsgFixture.ERROR_CLASS, - errorCodeAttribute.getErrorClass()); + assertEquals( + MsgFixture.ERROR_CLASS, + errorCodeAttribute.getErrorClass(), + "Error Class was not correctly decoded" + ); - assertEquals("Error Number was not correctly decoded", - MsgFixture.ERROR_NUMBER, - errorCodeAttribute.getErrorNumber()); - - assertEquals("Reason phrase was not correctly decoded", - MsgFixture.REASON_PHRASE.trim(), - errorCodeAttribute.getReasonPhrase().trim()); + assertEquals( + MsgFixture.ERROR_NUMBER, + errorCodeAttribute.getErrorNumber(), + "Error Number was not correctly decoded" + ); + assertEquals( + MsgFixture.REASON_PHRASE.trim(), + errorCodeAttribute.getReasonPhrase().trim(), + "Reason phrase was not correctly decoded"); } /** @@ -96,6 +94,7 @@ public class ErrorCodeAttributeTest extends TestCase { * * @throws StunException java.lang.Exception if we fail */ + @Test public void testEncode() throws StunException { @@ -108,8 +107,8 @@ public class ErrorCodeAttributeTest extends TestCase { byte[] actualReturn = errorCodeAttribute.encode(); - assertTrue("encode() did not return the expected binary array.", - Arrays.equals( expectedReturn, actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "encode() did not return the expected binary array."); } /** @@ -118,20 +117,17 @@ public class ErrorCodeAttributeTest extends TestCase { * * @throws StunException java.lang.Exception if we fail */ + @Test public void testEquals() throws StunException { - //null value test - ErrorCodeAttribute target = null; - boolean expectedReturn = false; - boolean actualReturn = errorCodeAttribute.equals(target); - assertEquals("equals() failed against a null value target.", - expectedReturn, actualReturn); + assertNotEquals(errorCodeAttribute, null, + "equals() failed against a null value target."); //different objects + ErrorCodeAttribute target; target = new ErrorCodeAttribute(); - expectedReturn = false; target.setErrorClass(MsgFixture.ERROR_CLASS); target.setErrorNumber(MsgFixture.ERROR_NUMBER); @@ -139,14 +135,12 @@ public class ErrorCodeAttributeTest extends TestCase { errorCodeAttribute.setErrorClass((byte)(MsgFixture.ERROR_CLASS+1)); errorCodeAttribute.setErrorNumber((byte)(MsgFixture.ERROR_NUMBER+1)); - actualReturn = errorCodeAttribute.equals(target); - assertEquals("equals() failed against a not equal target.", - expectedReturn, actualReturn); + assertNotEquals(errorCodeAttribute, target, + "equals() failed against a not equal target."); - //different objects + //equal objects target = new ErrorCodeAttribute(); errorCodeAttribute = new ErrorCodeAttribute(); - expectedReturn = true; target.setErrorClass(MsgFixture.ERROR_CLASS); target.setErrorNumber(MsgFixture.ERROR_NUMBER); @@ -154,11 +148,8 @@ public class ErrorCodeAttributeTest extends TestCase { errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS); errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER); - actualReturn = errorCodeAttribute.equals(target); - assertEquals("equals() failed against a not equal target.", - expectedReturn, actualReturn); - - + assertEquals(errorCodeAttribute, target, + "equals() failed against an equal target."); } /** @@ -166,6 +157,7 @@ public class ErrorCodeAttributeTest extends TestCase { * * @throws StunException java.lang.Exception if we fail */ + @Test public void testGetDataLength() throws StunException { @@ -177,16 +169,14 @@ public class ErrorCodeAttributeTest extends TestCase { errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE); char actualReturn = errorCodeAttribute.getDataLength(); - assertEquals("data length1", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, "data length1"); } /** * Test whether error code is properly calculated from error class and number - * - * @throws StunException java.lang.Exception if we fail */ + @Test public void testGetErrorCode() - throws StunException { char expectedReturn = (char)(100*MsgFixture.ERROR_CLASS + MsgFixture.ERROR_NUMBER); @@ -195,35 +185,36 @@ public class ErrorCodeAttributeTest extends TestCase { errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER); char actualReturn = errorCodeAttribute.getErrorCode(); - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } /** * Test whether we get a proper name for that attribute. */ + @Test public void testGetName() { - String expectedReturn = "ERROR-CODE"; - String actualReturn = errorCodeAttribute.getName(); - assertEquals("return value", expectedReturn, actualReturn); - + assertEquals("ERROR-CODE", errorCodeAttribute.getName()); } /** * Test whether error code is properly calculated from error class and number * - * @throws StunException java.lang.Exception if we fail */ - public void testSetErrorCode() throws StunException { + @Test + public void testSetErrorCode() + { char errorCode = (char)(MsgFixture.ERROR_CLASS*100 + MsgFixture.ERROR_NUMBER); errorCodeAttribute.setErrorCode(errorCode); - assertEquals("An error class was not properly set after decoding an error code.", - (int)MsgFixture.ERROR_CLASS, - (int)errorCodeAttribute.getErrorClass()); - assertEquals("An error number was not properly set after decoding an error code.", - (int)MsgFixture.ERROR_NUMBER, - (int)errorCodeAttribute.getErrorNumber()); + assertEquals( + MsgFixture.ERROR_CLASS, + (int) errorCodeAttribute.getErrorClass(), + "An error class was not properly set after decoding an error code." + ); + assertEquals( + MsgFixture.ERROR_NUMBER, + (int) errorCodeAttribute.getErrorNumber(), + "An error number was not properly set after decoding an error code." + ); } - - } diff --git a/src/test/java/org/ice4j/attribute/NonceAttributeTest.java b/src/test/java/org/ice4j/attribute/NonceAttributeTest.java index cb2ffd7..6fcba82 100644 --- a/src/test/java/org/ice4j/attribute/NonceAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/NonceAttributeTest.java @@ -17,19 +17,17 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Tests the nonce attribute class. * * @author Emil Ivov * @author Sebastien Vincent */ -public class NonceAttributeTest extends TestCase +public class NonceAttributeTest { private NonceAttribute nonceAttribute = null; MsgFixture msgFixture = null; @@ -40,30 +38,26 @@ public class NonceAttributeTest extends TestCase 0, (byte)nonceValue.length(), '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); msgFixture = new MsgFixture(); - nonceAttribute = new NonceAttribute(); nonceAttribute.setNonce(nonceValue.getBytes()); - - msgFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { nonceAttribute = null; - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } /** * Tests decoding of the nonce attribute. * @throws StunException upon a failure */ + @Test public void testDecodeAttributeBody() throws StunException { char offset = 0; @@ -72,63 +66,63 @@ public class NonceAttributeTest extends TestCase decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length); //nonce value - assertEquals( "decode failed", nonceAttribute, decoded); + assertEquals(nonceAttribute, decoded, "decode failed"); } /** * Tests the encode method */ + @Test public void testEncode() { - assertTrue("encode failed", - Arrays.equals(nonceAttribute.encode(), - attributeBinValue)); + assertArrayEquals(nonceAttribute.encode(), attributeBinValue, + "encode failed"); } /** * Test Equals */ + @Test public void testEquals() { NonceAttribute nonceAttribute2 = new NonceAttribute(); nonceAttribute2.setNonce(nonceValue.getBytes()); //test positive equals - assertEquals("testequals failed", nonceAttribute, nonceAttribute2); + assertEquals(nonceAttribute, nonceAttribute2); //test negative equals nonceAttribute2 = new NonceAttribute(); nonceAttribute2.setNonce("some other nonce".getBytes()); //test positive equals - assertFalse("testequals failed", - nonceAttribute.equals(nonceAttribute2)); + assertNotEquals(nonceAttribute2, nonceAttribute); //test null equals - assertFalse("testequals failed", - nonceAttribute.equals(null)); + assertNotEquals(nonceAttribute, null); } /** * Tests extracting data length */ + @Test public void testGetDataLength() { char expectedReturn = (char)nonceValue.length(); char actualReturn = nonceAttribute.getDataLength(); - assertEquals("getDataLength - failed", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } /** * Tests getting the name */ + @Test public void testGetName() { - String expectedReturn = "NONCE"; - String actualReturn = nonceAttribute.getName(); - assertEquals("getting name failed", expectedReturn, actualReturn); + assertEquals("NONCE", nonceAttribute.getName()); } + @Test public void testSetGetNonce() { byte[] expectedReturn = nonceValue.getBytes(); @@ -137,8 +131,7 @@ public class NonceAttributeTest extends TestCase att.setNonce(expectedReturn); byte[] actualReturn = att.getNonce(); - assertTrue("nonce setter or getter failed", - Arrays.equals( expectedReturn, - actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "nonce setter or getter failed"); } } diff --git a/src/test/java/org/ice4j/attribute/OptionalAttributeAttributeTest.java b/src/test/java/org/ice4j/attribute/OptionalAttributeAttributeTest.java index 91ed08c..96b4c2e 100644 --- a/src/test/java/org/ice4j/attribute/OptionalAttributeAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/OptionalAttributeAttributeTest.java @@ -17,25 +17,22 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.Arrays; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * @author Emil Ivov */ -public class OptionalAttributeAttributeTest extends TestCase +public class OptionalAttributeAttributeTest { private OptionalAttribute optionalAttribute = null; private MsgFixture msgFixture = null; byte[] expectedAttributeValue = null; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); - msgFixture = new MsgFixture(); int offset = Attribute.HEADER_LENGTH; @@ -51,17 +48,18 @@ public class OptionalAttributeAttributeTest extends TestCase msgFixture.optionalAttributeType); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { optionalAttribute = null; expectedAttributeValue = null; - super.tearDown(); } /** * Test whether sample binary arrays are correctly decoded. * @throws StunException if anything goes wrong. */ + @Test public void testDecodeAttributeBody() throws StunException { char offset = Attribute.HEADER_LENGTH; @@ -70,60 +68,52 @@ public class OptionalAttributeAttributeTest extends TestCase optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute, offset, length); + assertArrayEquals( + expectedAttributeValue, optionalAttribute.getBody(), + "OptionalAttribute did not decode properly."); - assertTrue("OptionalAttribute did not decode properly.", - Arrays.equals( expectedAttributeValue, - optionalAttribute.getBody())); - - assertEquals("Lenght was not properly decoded", length, - optionalAttribute.getDataLength()); - + assertEquals(length, optionalAttribute.getDataLength(), + "Length was not properly decoded"); } /** * Test whether attributes are properly encoded */ + @Test public void testEncode() { optionalAttribute.setBody(expectedAttributeValue, 0, expectedAttributeValue.length); byte[] actualReturn = optionalAttribute.encode(); - - assertTrue("encode failed", - Arrays.equals( msgFixture.unknownOptionalAttribute, actualReturn) ); + assertArrayEquals(msgFixture.unknownOptionalAttribute, actualReturn); } /** * Test whether the equals method works ok */ + @Test public void testEquals() { //null comparison - Object obj = null; - boolean expectedReturn = false; optionalAttribute.setBody( expectedAttributeValue, 0, expectedAttributeValue.length); - boolean actualReturn = optionalAttribute.equals(obj); - assertEquals("failed null comparison", expectedReturn, actualReturn); + assertNotEquals(optionalAttribute, null); //wrong type comparison - obj = "hehe :)"; - actualReturn = optionalAttribute.equals(obj); - assertEquals("failed wrong type comparison", expectedReturn, - actualReturn); + assertNotEquals(optionalAttribute, "hehe :)"); //succesful comparison - obj = new OptionalAttribute(msgFixture.optionalAttributeType); + OptionalAttribute obj = + new OptionalAttribute(msgFixture.optionalAttributeType); - ((OptionalAttribute)obj).setBody( expectedAttributeValue, 0, + obj.setBody( expectedAttributeValue, 0, expectedAttributeValue.length); - expectedReturn = true; - actualReturn = optionalAttribute.equals(obj); - assertEquals("failed null comparison", expectedReturn, actualReturn); + assertEquals(obj, optionalAttribute); } + @Test public void testGetDataLength() { char expectedReturn = (char)expectedAttributeValue.length; @@ -132,7 +122,7 @@ public class OptionalAttributeAttributeTest extends TestCase expectedAttributeValue.length); char actualReturn = optionalAttribute.getDataLength(); - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } } diff --git a/src/test/java/org/ice4j/attribute/RealmAttributeTest.java b/src/test/java/org/ice4j/attribute/RealmAttributeTest.java index 6335e7f..0a3e7ac 100644 --- a/src/test/java/org/ice4j/attribute/RealmAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/RealmAttributeTest.java @@ -17,19 +17,17 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Tests the realm attribute class. * * @author Emil Ivov * @author Sebastien Vincent */ -public class RealmAttributeTest extends TestCase +public class RealmAttributeTest { private RealmAttribute realmAttribute = null; MsgFixture msgFixture = null; @@ -40,30 +38,27 @@ public class RealmAttributeTest extends TestCase 0, (byte)realmValue.length(), 'd', 'o', 'm', 'a', 'i', 'n', '.', 'o', 'r', 'g', 0x00, 0x00}; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); msgFixture = new MsgFixture(); realmAttribute = new RealmAttribute(); realmAttribute.setRealm(realmValue.getBytes()); - - msgFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { realmAttribute = null; - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } /** * Tests decoding of the realm attribute. * @throws StunException upon a failure */ + @Test public void testDecodeAttributeBody() throws StunException { char offset = 0; @@ -72,63 +67,62 @@ public class RealmAttributeTest extends TestCase decoded.decodeAttributeBody(realmValue.getBytes(), offset, length); //realm value - assertEquals( "decode failed", realmAttribute, decoded); + assertEquals(realmAttribute, decoded); } /** * Tests the encode method */ + @Test public void testEncode() { - assertTrue("encode failed", - Arrays.equals(realmAttribute.encode(), - attributeBinValue)); + assertArrayEquals(realmAttribute.encode(), attributeBinValue); } /** * Test Equals */ + @Test public void testEquals() { RealmAttribute realmAttribute2 = new RealmAttribute(); realmAttribute2.setRealm(realmValue.getBytes()); //test positive equals - assertEquals("testequals failed", realmAttribute, realmAttribute2); + assertEquals(realmAttribute, realmAttribute2); //test negative equals realmAttribute2 = new RealmAttribute(); realmAttribute2.setRealm("some other realm".getBytes()); //test positive equals - assertFalse("testequals failed", - realmAttribute.equals(realmAttribute2)); + assertNotEquals(realmAttribute2, realmAttribute); //test null equals - assertFalse("testequals failed", - realmAttribute.equals(null)); + assertNotEquals(realmAttribute, null); } /** * Tests extracting data length */ + @Test public void testGetDataLength() { char expectedReturn = (char)realmValue.length(); char actualReturn = realmAttribute.getDataLength(); - assertEquals("getDataLength - failed", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } /** * Tests getting the name */ + @Test public void testGetName() { - String expectedReturn = "REALM"; - String actualReturn = realmAttribute.getName(); - assertEquals("getting name failed", expectedReturn, actualReturn); + assertEquals("REALM", realmAttribute.getName()); } + @Test public void testSetGetRealm() { byte[] expectedReturn = realmValue.getBytes(); @@ -137,8 +131,7 @@ public class RealmAttributeTest extends TestCase att.setRealm(expectedReturn); byte[] actualReturn = att.getRealm(); - assertTrue("realm setter or getter failed", - Arrays.equals( expectedReturn, - actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "realm setter or getter failed"); } } diff --git a/src/test/java/org/ice4j/attribute/RequestedAddressFamilyAttributeTest.java b/src/test/java/org/ice4j/attribute/RequestedAddressFamilyAttributeTest.java index fca5d38..da12f26 100644 --- a/src/test/java/org/ice4j/attribute/RequestedAddressFamilyAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/RequestedAddressFamilyAttributeTest.java @@ -17,12 +17,10 @@ */ package org.ice4j.attribute; -import java.util.*; - -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Class to test the RequestedAddressFamilyAttribute class. * @@ -30,42 +28,31 @@ import org.ice4j.*; * */ public class RequestedAddressFamilyAttributeTest - extends TestCase { private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute = null; private MsgFixture msgFixture; - @Override - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); this.requestedAddressFamilyAttribute = new RequestedAddressFamilyAttribute(); this.msgFixture = new MsgFixture(); - - msgFixture.setUp(); } - public RequestedAddressFamilyAttributeTest(String name) - { - super(name); - } - - @Override - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { this.requestedAddressFamilyAttribute = null; - this.msgFixture.tearDown(); - this.msgFixture = null; - super.tearDown(); } /** * Tests whether data length is properly calculated. */ + @Test public void testGetDataLength() { char expectedReturn = 1; @@ -73,47 +60,39 @@ public class RequestedAddressFamilyAttributeTest .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); char actualReturn = this.requestedAddressFamilyAttribute.getDataLength(); - assertEquals( - "Datalength is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "Datalength is not properly calculated"); expectedReturn = 1; this.requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); actualReturn = this.requestedAddressFamilyAttribute.getDataLength(); - assertEquals( - "Datalength is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "Datalength is not properly calculated"); } /** * Tests getting the name. */ + @Test public void testGetName() { - String expectedReturn = "REQUESTED-ADDRESS-FAMILY"; - String actualReturn = requestedAddressFamilyAttribute.getName(); - assertEquals( - "getting name failed", expectedReturn, actualReturn); + assertEquals("REQUESTED-ADDRESS-FAMILY", requestedAddressFamilyAttribute.getName()); } /** * Tests the equals method against a null, a different and an identical * object. */ + @Test public void testEqualsObject() { // null test - RequestedAddressFamilyAttribute target = null; - boolean expectedReturn = false; - boolean actualReturn = requestedAddressFamilyAttribute.equals(target); - - assertEquals( - "RequestedAddressFamilyAttribute.equals() failed against a null " - + "target.", expectedReturn, actualReturn); + assertNotEquals(requestedAddressFamilyAttribute, null); // difference test + RequestedAddressFamilyAttribute target; target = new RequestedAddressFamilyAttribute(); char family = MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6; @@ -122,20 +101,12 @@ public class RequestedAddressFamilyAttributeTest requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); - expectedReturn = false; - actualReturn = requestedAddressFamilyAttribute.equals(target); - assertEquals( - "RequestedAddressFamilyAttribute.equals() failed against a " - + "different target.", expectedReturn, actualReturn); + assertNotEquals(requestedAddressFamilyAttribute, target); // equality test target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); - expectedReturn = true; - actualReturn = requestedAddressFamilyAttribute.equals(target); - assertEquals( - "RequestedAddressFamilyAttribute.equals() failed against an equal " - + "target.", expectedReturn, actualReturn); + assertEquals(requestedAddressFamilyAttribute, target); // ipv6 equality test target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); @@ -143,11 +114,7 @@ public class RequestedAddressFamilyAttributeTest requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); - expectedReturn = true; - actualReturn = requestedAddressFamilyAttribute.equals(target); - assertEquals( - "RequestedAddressFamilyAttribute.equals() failed for IPv6 address.", - expectedReturn, actualReturn); + assertEquals(requestedAddressFamilyAttribute, target); } /** @@ -156,6 +123,7 @@ public class RequestedAddressFamilyAttributeTest * @throws StunException if something goes wrong while decoding * Attribute Body. */ + @Test public void testDecodeAttributeBodyV4() throws StunException { byte[] attributeValue = msgFixture.requestedAddressFamilyV4; @@ -166,10 +134,10 @@ public class RequestedAddressFamilyAttributeTest attributeValue, offset, length); assertEquals( - "RequestedAddressFamilyAttribute.decode() did not properly decode " - + "the family field.", MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4, - requestedAddressFamilyAttribute.getFamily()); + requestedAddressFamilyAttribute.getFamily(), + "RequestedAddressFamilyAttribute.decode() did not properly decode the family field." + ); } /** @@ -178,7 +146,8 @@ public class RequestedAddressFamilyAttributeTest * @throws StunException if something goes wrong while decoding * Attribute Body. */ - public void testDecodeAttributeBodyV6() throws StunException + @Test + public void testDecodeAttributeBodyV6() throws StunException { byte[] attributeValue = msgFixture.requestedAddressFamilyV6; char offset = Attribute.HEADER_LENGTH; @@ -188,63 +157,62 @@ public class RequestedAddressFamilyAttributeTest attributeValue, offset, length); assertEquals( - "RequestedAddressFamilyAttribute.decode() did not properly decode.", MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6, - requestedAddressFamilyAttribute.getFamily()); + requestedAddressFamilyAttribute.getFamily(), + "RequestedAddressFamilyAttribute.decode() did not properly decode." + ); } /** * Test whether attributes are properly encoded. */ + @Test public void testEncodeV4() { byte[] expectedReturn = msgFixture.requestedAddressFamilyV4; requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); byte[] actualReturn = requestedAddressFamilyAttribute.encode(); - assertTrue( - "RequestedAddressFamilyAttribute.encode() did not " - + "properly encode a sample attribute for IPv4 family", - Arrays.equals( - expectedReturn, actualReturn)); + assertArrayEquals( + expectedReturn, actualReturn, + "RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv4 family" + ); } /** * Test whether attributes are properly encoded. */ + @Test public void testEncodeV6() { byte[] expectedReturn = msgFixture.requestedAddressFamilyV6; requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); byte[] actualReturn = requestedAddressFamilyAttribute.encode(); - assertTrue( - "RequestedAddressFamilyAttribute.encode() did not " - + "properly encode a sample attribute for IPv6 family", - Arrays.equals( - expectedReturn, actualReturn)); + assertArrayEquals( + expectedReturn, actualReturn, + "RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv6 family" + ); } /** * Tests that the address family is always 0x01 or 0x02. */ + @Test public void testGetFamily() { char expectedReturn = 0x01; this.requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); char actualReturn = this.requestedAddressFamilyAttribute.getFamily(); - assertEquals( - "Family is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "Family is not properly calculated"); expectedReturn = 0x02; this.requestedAddressFamilyAttribute .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); actualReturn = this.requestedAddressFamilyAttribute.getFamily(); - assertEquals( - "Family is not properly calculated", expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "Family is not properly calculated"); } - } diff --git a/src/test/java/org/ice4j/attribute/SoftwareAttributeTest.java b/src/test/java/org/ice4j/attribute/SoftwareAttributeTest.java index 4ec5f91..6de3c79 100644 --- a/src/test/java/org/ice4j/attribute/SoftwareAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/SoftwareAttributeTest.java @@ -17,18 +17,16 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Tests the software attribute class. * * @author Emil Ivov */ -public class SoftwareAttributeTest extends TestCase +public class SoftwareAttributeTest { private SoftwareAttribute softwareAttribute = null; MsgFixture msgFixture = null; @@ -40,30 +38,27 @@ public class SoftwareAttributeTest extends TestCase 't', 'u', 'r', 'n', 's', 'e', 'r','v', 'e', 'r', '.', 'o', 'r', 'g', 0x00, 0x00}; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); msgFixture = new MsgFixture(); softwareAttribute = new SoftwareAttribute(); softwareAttribute.setSoftware(softwareValue.getBytes()); - - msgFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { softwareAttribute = null; - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } /** * Tests decoding of the software attribute. * @throws StunException upon a failure */ + @Test public void testDecodeAttributeBody() throws StunException { char offset = 0; @@ -72,63 +67,62 @@ public class SoftwareAttributeTest extends TestCase decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length); //software value - assertEquals( "decode failed", softwareAttribute, decoded); + assertEquals(softwareAttribute, decoded); } /** * Tests the encode method */ + @Test public void testEncode() { - assertTrue("encode failed", - Arrays.equals(softwareAttribute.encode(), - attributeBinValue)); + assertArrayEquals(softwareAttribute.encode(), attributeBinValue); } /** * Test Equals */ + @Test public void testEquals() { SoftwareAttribute softwareAttribute2 = new SoftwareAttribute(); softwareAttribute2.setSoftware(softwareValue.getBytes()); //test positive equals - assertEquals("testequals failed", softwareAttribute, softwareAttribute2); + assertEquals(softwareAttribute, softwareAttribute2); //test negative equals softwareAttribute2 = new SoftwareAttribute(); softwareAttribute2.setSoftware("some other software".getBytes()); //test positive equals - assertFalse("testequals failed", - softwareAttribute.equals(softwareAttribute2)); + assertNotEquals(softwareAttribute2, softwareAttribute); //test null equals - assertFalse("testequals failed", - softwareAttribute.equals(null)); + assertNotEquals(softwareAttribute, null); } /** * Tests extracting data length */ + @Test public void testGetDataLength() { char expectedReturn = (char)softwareValue.length(); char actualReturn = softwareAttribute.getDataLength(); - assertEquals("getDataLength - failed", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } /** * Tests getting the name */ + @Test public void testGetName() { - String expectedReturn = "SOFTWARE"; - String actualReturn = softwareAttribute.getName(); - assertEquals("getting name failed", expectedReturn, actualReturn); + assertEquals("SOFTWARE", softwareAttribute.getName()); } + @Test public void testSetGetSoftware() { byte[] expectedReturn = softwareValue.getBytes(); @@ -137,8 +131,7 @@ public class SoftwareAttributeTest extends TestCase att.setSoftware(expectedReturn); byte[] actualReturn = att.getSoftware(); - assertTrue("software setter or getter failed", - Arrays.equals( expectedReturn, - actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "software setter or getter failed"); } } diff --git a/src/test/java/org/ice4j/attribute/UnknownAttributesAttributeTest.java b/src/test/java/org/ice4j/attribute/UnknownAttributesAttributeTest.java index 7356fd2..c2d008b 100644 --- a/src/test/java/org/ice4j/attribute/UnknownAttributesAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/UnknownAttributesAttributeTest.java @@ -17,58 +17,49 @@ */ package org.ice4j.attribute; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Tests the UNKNOWN attribute class. * * @author Emil Ivov */ -public class UnknownAttributesAttributeTest extends TestCase +public class UnknownAttributesAttributeTest { private UnknownAttributesAttribute unknownAttributesAttribute = null; private MsgFixture binMessagesFixture; - public UnknownAttributesAttributeTest(String name) + @BeforeEach + public void setUp() throws Exception { - super(name); - } - - protected void setUp() throws Exception - { - super.setUp(); unknownAttributesAttribute = new UnknownAttributesAttribute(); binMessagesFixture = new MsgFixture(); - - binMessagesFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { unknownAttributesAttribute = null; - binMessagesFixture.tearDown(); - binMessagesFixture = null; - super.tearDown(); } //-------------------------------- TESTS --------------------------------------- /** * Verify the the constructed object has the correct (UNKNOWN-ATTRIBUTES) * type. */ + @Test public void testUnknownAttributesAttribute() { unknownAttributesAttribute = new UnknownAttributesAttribute(); - - assertEquals("UnknownAttributesAttribute() did not properly set the " - +"Attribute's type field!", - (int)Attribute.UNKNOWN_ATTRIBUTES, - (int)unknownAttributesAttribute.getAttributeType() - ); + assertEquals( + Attribute.UNKNOWN_ATTRIBUTES, + (int) unknownAttributesAttribute.getAttributeType(), + "UnknownAttributesAttribute() did not properly set the Attribute's type field!" + ); } /** @@ -76,37 +67,40 @@ public class UnknownAttributesAttributeTest extends TestCase * and that a second addition of the same id would not augment the attribute * count. */ + @Test public void testAddAttributeID() { char attributeID = 0x22; // unknown attribute id unknownAttributesAttribute.addAttributeID(attributeID); - assertEquals("addAttributeID does not seem to properly add the attribute ID", - (int)attributeID, - (int)unknownAttributesAttribute.getAttribute(0) - ); + assertEquals( + (int) attributeID, + (int) unknownAttributesAttribute.getAttribute(0), + "addAttributeID does not seem to properly add the attribute ID" + ); - assertEquals("addAttributeID does not seem to properly add the attribute ID", - 1, - unknownAttributesAttribute.getAttributeCount() - ); + assertEquals( + 1, + unknownAttributesAttribute.getAttributeCount(), + "addAttributeID does not seem to properly add the attribute ID" + ); //add a second one unknownAttributesAttribute.addAttributeID(attributeID); - assertEquals("Adding a 2nd time the same attributeID should not change " - +"the number of attributes", - 1, - unknownAttributesAttribute.getAttributeCount() - ); - + assertEquals( + 1, + unknownAttributesAttribute.getAttributeCount(), + "Adding a 2nd time the same attributeID should not change the number of attributes" + ); } /** * Tests whether a sample binary array is properly decoded. * @throws StunException if anything goes wrong. */ + @Test public void testDecodeAttributeBody() throws StunException { //a copy of the array in the fixture: @@ -118,37 +112,44 @@ public class UnknownAttributesAttributeTest extends TestCase - Attribute.HEADER_LENGTH)); //is every one there? assertTrue( - "The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT +" attribute id " - + "was not found after decoding a binary array that contained it.", unknownAttributesAttribute.contains( - MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT)); + MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT), + "The " + (int) MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT + + " attribute id " + + "was not found after decoding a binary array that contained it." + ); assertTrue( - "The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT +" attribute id " - + "was not found after decoding a binary array that contained it.", unknownAttributesAttribute.contains( - MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT)); + MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT), + "The " + (int) MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT + + " attribute id " + + "was not found after decoding a binary array that contained it." + ); assertTrue( - "The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT +" attribute id " - + "was not found after decoding a binary array that contained it.", unknownAttributesAttribute.contains( - MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT)); + MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT), + "The " + (int) MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT + + " attribute id " + + "was not found after decoding a binary array that contained it." + ); - - assertEquals("The decoded attribute contained " - + unknownAttributesAttribute.getAttributeCount() - + " attribute ids when there were only " - + (int)MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST - + " in the original binary array.", - MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST, - unknownAttributesAttribute.getAttributeCount() - ); + assertEquals( + MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST, + unknownAttributesAttribute.getAttributeCount(), + "The decoded attribute contained " + + unknownAttributesAttribute.getAttributeCount() + + " attribute ids when there were only " + + (int) MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST + + " in the original binary array." + ); } /** * Creates a new UnknownAttributesAttribute encodes it and assert equality * with binMessagesFixture.unknownAttsEncodeExpectedResult. */ + @Test public void testEncode() { byte[] expectedReturn = binMessagesFixture.unknownAttsEncodeExpectedResult; @@ -158,46 +159,36 @@ public class UnknownAttributesAttributeTest extends TestCase unknownAttributesAttribute.addAttributeID( MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT); - - byte[] actualReturn = unknownAttributesAttribute.encode(); - assertTrue("UnknownAttributesAttribute did not encode properly.", - Arrays.equals(actualReturn, expectedReturn)); + assertArrayEquals(actualReturn, expectedReturn); } /** * Tests the equals method against a null, a different and an identical * object. */ + @Test public void testEquals() { UnknownAttributesAttribute target = new UnknownAttributesAttribute(); - boolean expectedReturn = false; - boolean actualReturn = unknownAttributesAttribute.equals(null); - assertEquals("Equals failed for a null object", - expectedReturn, actualReturn); + assertNotEquals(unknownAttributesAttribute, null); unknownAttributesAttribute.addAttributeID((char)25); target.addAttributeID((char)25); unknownAttributesAttribute.addAttributeID((char)26); - actualReturn = unknownAttributesAttribute.equals(target); - assertEquals("Equals failed when comparing different objects.", - expectedReturn, actualReturn); + assertNotEquals(unknownAttributesAttribute, target); target.addAttributeID((char)26); - expectedReturn = true; - actualReturn = unknownAttributesAttribute.equals(target); - assertEquals("Equals failed to recognize identical objects.", - expectedReturn, actualReturn); - + assertEquals(unknownAttributesAttribute, target); } /** * Tests that getAttribute() return the correct attribute id, preserving * entry order. */ + @Test public void testGetAttribute() { char expectedId1 = 20; @@ -212,14 +203,15 @@ public class UnknownAttributesAttributeTest extends TestCase actualId1 = unknownAttributesAttribute.getAttribute(0); actualId2 = unknownAttributesAttribute.getAttribute(1); - assertEquals("getAttribute() return value mismatch", expectedId1, actualId1); - assertEquals("getAttribute() return value mismatch", expectedId2, actualId2); + assertEquals(expectedId1, actualId1, "getAttribute() return value mismatch"); + assertEquals(expectedId2, actualId2, "getAttribute() return value mismatch"); } /** * Add some attributes and test whether their number is properly calculated. * Tests duplicate id handling as well. */ + @Test public void testGetAttributeCount() { int expectedReturn = 5; @@ -232,14 +224,15 @@ public class UnknownAttributesAttributeTest extends TestCase unknownAttributesAttribute.addAttributeID((char)25);//duplicate values should be ignored int actualReturn = unknownAttributesAttribute.getAttributeCount(); - assertEquals("getAttributeCount did not return the expected value", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "getAttributeCount did not return the expected value"); } /** * Same as testGetAttributeID, only attribute attributes are extracted * through the getAttributes()'s iterator. */ + @Test public void testGetAttributes() { char expectedId1 = 20; @@ -256,10 +249,8 @@ public class UnknownAttributesAttributeTest extends TestCase actualId1 = iterator.next(); actualId2 = iterator.next(); - assertEquals("getAttributes() return value mismatch", expectedId1, actualId1); - assertEquals("getAttributes() return value mismatch", expectedId2, actualId2); - - + assertEquals(expectedId1, actualId1, "getAttributes() return value mismatch"); + assertEquals(expectedId2, actualId2, "getAttributes() return value mismatch"); } /** @@ -267,6 +258,7 @@ public class UnknownAttributesAttributeTest extends TestCase * Test is first performed for an odd number of attributes and then again * (after adding another attribute id). Both results should be the same. */ + @Test public void testGetDataLength() { char expectedReturn = 8; @@ -276,25 +268,23 @@ public class UnknownAttributesAttributeTest extends TestCase unknownAttributesAttribute.addAttributeID((char)22); char actualReturn = unknownAttributesAttribute.getDataLength(); - assertEquals("Incorrect testGetDataLength() return value", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "Incorrect testGetDataLength() return value"); unknownAttributesAttribute.addAttributeID((char)23); actualReturn = unknownAttributesAttribute.getDataLength(); - assertEquals("Incorrect testGetDataLength() return value", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "Incorrect testGetDataLength() return value"); } /** * Tests whether getName returns a relevant name. */ + @Test public void testGetName() { - String expectedReturn = "UNKNOWN-ATTRIBUTES"; - String actualReturn = unknownAttributesAttribute.getName(); - assertEquals("getName() return", expectedReturn, actualReturn); + assertEquals("UNKNOWN-ATTRIBUTES", unknownAttributesAttribute.getName()); } - } diff --git a/src/test/java/org/ice4j/attribute/UsernameAttributeTest.java b/src/test/java/org/ice4j/attribute/UsernameAttributeTest.java index 1944a80..f0544ea 100644 --- a/src/test/java/org/ice4j/attribute/UsernameAttributeTest.java +++ b/src/test/java/org/ice4j/attribute/UsernameAttributeTest.java @@ -17,19 +17,17 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * Tests the username attribute class. * * @author Emil Ivov * @author Sebastien Vincent */ -public class UsernameAttributeTest extends TestCase +public class UsernameAttributeTest { private UsernameAttribute usernameAttribute = null; MsgFixture msgFixture = null; @@ -40,30 +38,27 @@ public class UsernameAttributeTest extends TestCase 0, (byte)usernameValue.length(), 'u', 's', 'e', 'r', 'n', 'a', 'm','e'}; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); msgFixture = new MsgFixture(); usernameAttribute = new UsernameAttribute(); usernameAttribute.setUsername(usernameValue.getBytes()); - - msgFixture.setUp(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { usernameAttribute = null; - msgFixture.tearDown(); - msgFixture = null; - super.tearDown(); } /** * Tests decoding of the username attribute. * @throws StunException upon a failure */ + @Test public void testDecodeAttributeBody() throws StunException { char offset = 0; @@ -72,63 +67,62 @@ public class UsernameAttributeTest extends TestCase decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length); //username value - assertEquals( "decode failed", usernameAttribute, decoded); + assertEquals(usernameAttribute, decoded); } /** * Tests the encode method */ + @Test public void testEncode() { - assertTrue("encode failed", - Arrays.equals(usernameAttribute.encode(), - attributeBinValue)); + assertArrayEquals(usernameAttribute.encode(), attributeBinValue); } /** * Test Equals */ + @Test public void testEquals() { UsernameAttribute usernameAttribute2 = new UsernameAttribute(); usernameAttribute2.setUsername(usernameValue.getBytes()); //test positive equals - assertEquals("testequals failed", usernameAttribute, usernameAttribute2); + assertEquals(usernameAttribute, usernameAttribute2); //test negative equals usernameAttribute2 = new UsernameAttribute(); usernameAttribute2.setUsername("some other username".getBytes()); //test positive equals - assertFalse("testequals failed", - usernameAttribute.equals(usernameAttribute2)); + assertNotEquals(usernameAttribute2, usernameAttribute); //test null equals - assertFalse("testequals failed", - usernameAttribute.equals(null)); + assertNotEquals(usernameAttribute, null); } /** * Tests extracting data length */ + @Test public void testGetDataLength() { char expectedReturn = (char)usernameValue.length(); char actualReturn = usernameAttribute.getDataLength(); - assertEquals("getDataLength - failed", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } /** * Tests getting the name */ + @Test public void testGetName() { - String expectedReturn = "USERNAME"; - String actualReturn = usernameAttribute.getName(); - assertEquals("getting name failed", expectedReturn, actualReturn); + assertEquals("USERNAME", usernameAttribute.getName()); } + @Test public void testSetGetUsername() { byte[] expectedReturn = usernameValue.getBytes(); @@ -137,8 +131,7 @@ public class UsernameAttributeTest extends TestCase att.setUsername(expectedReturn); byte[] actualReturn = att.getUsername(); - assertTrue("username setter or getter failed", - Arrays.equals( expectedReturn, - actualReturn)); + assertArrayEquals(expectedReturn, actualReturn, + "username setter or getter failed"); } } diff --git a/src/test/java/org/ice4j/attribute/XorOnlyTest.java b/src/test/java/org/ice4j/attribute/XorOnlyTest.java index b975484..b16fd82 100644 --- a/src/test/java/org/ice4j/attribute/XorOnlyTest.java +++ b/src/test/java/org/ice4j/attribute/XorOnlyTest.java @@ -17,32 +17,30 @@ */ package org.ice4j.attribute; -import junit.framework.*; - -import java.util.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; - +import org.junit.jupiter.api.*; /** * @author Emil Ivov */ -public class XorOnlyTest extends TestCase +public class XorOnlyTest { private XorOnlyAttribute xorOnly = null; private MsgFixture msgFixture = null; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); xorOnly = new XorOnlyAttribute(); msgFixture = new MsgFixture(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { xorOnly = null; msgFixture = null; - super.tearDown(); } /** @@ -50,6 +48,7 @@ public class XorOnlyTest extends TestCase * decode method doesn't do anything in the XorOnly att. * @throws StunException if sth happens */ + @Test public void testDecodeAttributeBody() throws StunException { byte[] attributeValue = new byte[]{}; @@ -61,52 +60,52 @@ public class XorOnlyTest extends TestCase /** * Test encoding XorOnly attributes. */ + @Test public void testEncode() { byte[] expectedReturn = new byte[]{Attribute.XOR_ONLY>>8, Attribute.XOR_ONLY&0x00FF, 0, 0}; byte[] actualReturn = xorOnly.encode(); - assertTrue("XorOnly failed to encode", - Arrays.equals( expectedReturn, actualReturn)); + assertArrayEquals(expectedReturn, actualReturn); } /** * Test positive and negative XorOnly.equals() returns * @throws Exception if decoding fails */ + @Test public void testEquals() throws Exception { XorOnlyAttribute xor2 = new XorOnlyAttribute(); - assertEquals("equals() failes for XorOnly", xorOnly, xor2); + assertEquals(xorOnly, xor2); MappedAddressAttribute maatt = new MappedAddressAttribute(); maatt.decodeAttributeBody( msgFixture.mappedAddress, (char) 0, (char) msgFixture.mappedAddress.length ); - - assertFalse("equals failed to see a difference", xorOnly.equals(maatt)); - assertFalse("equals failed for null", xorOnly.equals(null)); + assertNotEquals(maatt, xorOnly); + assertNotEquals(xorOnly, null); } /** * Makes sure the data langth is 0 */ + @Test public void testGetDataLength() { char expectedReturn = 0; char actualReturn = xorOnly.getDataLength(); - assertEquals("data length was not 0", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, "data length was not 0"); } /** * Verifies the name (do we really need this?). */ + @Test public void testGetName() { - String expectedReturn = "XOR-ONLY"; - String actualReturn = xorOnly.getName(); - assertEquals("Is name correct", expectedReturn, actualReturn); + assertEquals("XOR-ONLY", xorOnly.getName()); } } diff --git a/src/test/java/org/ice4j/ice/NetworkUtilsTest.java b/src/test/java/org/ice4j/ice/NetworkUtilsTest.java index df88e53..69ffb24 100644 --- a/src/test/java/org/ice4j/ice/NetworkUtilsTest.java +++ b/src/test/java/org/ice4j/ice/NetworkUtilsTest.java @@ -17,9 +17,9 @@ */ package org.ice4j.ice; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; -import org.junit.*; +import org.junit.jupiter.api.*; public class NetworkUtilsTest { diff --git a/src/test/java/org/ice4j/ice/RoleConflictResolutionTest.java b/src/test/java/org/ice4j/ice/RoleConflictResolutionTest.java index c57e918..544b2c8 100644 --- a/src/test/java/org/ice4j/ice/RoleConflictResolutionTest.java +++ b/src/test/java/org/ice4j/ice/RoleConflictResolutionTest.java @@ -1,196 +1,198 @@ -/* - * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. - * - * Copyright @ 2019 8x8, Inc - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.ice4j.ice; - -import org.ice4j.*; -import org.junit.*; - -import java.io.*; -import java.util.*; -import java.util.concurrent.*; -import java.util.logging.*; - -/** - * RoleConflictResolutionTest set of tests which does end-to-end test - * of ICE role conflict recovery. - * - * @author Yura Yaroshevich - */ -public class RoleConflictResolutionTest -{ - protected static final Logger logger - = Logger.getLogger(RoleConflictResolutionTest.class.getName()); - - @Test - public void testRecoveryFromBothControlledConflict() - throws Throwable - { - testRecoveryFromRoleConflict(false); - } - - @Test - public void testRecoveryFromBothControllingConflict() - throws Throwable - { - testRecoveryFromRoleConflict(true); - } - - private static void testRecoveryFromRoleConflict(boolean bothControlling) - throws Throwable - { - final Agent peer1 = createPeer("[peer-1]", bothControlling); - // Set explicit tie-breakers to avoid automatic conflict resolution - peer1.setTieBreaker(1); - - final Agent peer2 = createPeer("[peer-2]", bothControlling); - peer1.setTieBreaker(2); - - final CountDownLatch countDownLatch = new CountDownLatch(2); - - for (Agent peer : Arrays.asList(peer1, peer2)) - { - peer.addStateChangeListener(evt -> - { - logger.info(peer.toString() + ": state changed to " - + evt.toString()); - if (peer.getState().isEstablished()) - { - countDownLatch.countDown(); - } - }); - } - - exchangeCredentials(peer1, peer2); - exchangeCandidates(peer1, peer2); - - peer1.startConnectivityEstablishment(); - peer2.startConnectivityEstablishment(); - - boolean isConnected = countDownLatch.await(20, TimeUnit.SECONDS); - - logSelectedPairs(peer1); - logSelectedPairs(peer2); - - Assert.assertTrue("Expected connection established within time out", - isConnected); - Assert.assertTrue("peer 1 connectivity", - peer1.getState().isEstablished()); - Assert.assertTrue("peer 2 connectivity", - peer2.getState().isEstablished()); - - disposePeer(peer1); - disposePeer(peer2); - } - - private static Agent createPeer(String label, boolean iceControlling) - throws IOException - { - final Agent agent = new Agent(label, null); - agent.setControlling(iceControlling); - IceMediaStream iceStream = agent.createMediaStream("media-stream"); - - agent.createComponent( - iceStream, - Transport.UDP, - 0x400, 0x400, 0xFFFF, - KeepAliveStrategy.ALL_SUCCEEDED, - true); - - return agent; - } - - private static void disposePeer(Agent peer) - { - peer.free(); - } - - private static void logSelectedPairs(Agent peer) - { - for (IceMediaStream stream : peer.getStreams()) - { - for (Component component : stream.getComponents()) - { - CandidatePair selectedPair = component.getSelectedPair(); - if (selectedPair != null) - { - logger.info( peer.toString() + ": selected pair for " + - "component " + component.getName() + " :" + - selectedPair.toString()); - } - } - } - } - - private static void exchangeCredentials(Agent peer1, Agent peer2) - { - for(IceMediaStream stream : peer2.getStreams()) - { - stream.setRemoteUfrag(peer1.getLocalUfrag()); - stream.setRemotePassword(peer1.getLocalPassword()); - } - - for(IceMediaStream stream : peer1.getStreams()) - { - stream.setRemoteUfrag(peer2.getLocalUfrag()); - stream.setRemotePassword(peer2.getLocalPassword()); - } - } - - private static void exchangeCandidates(Agent peer1, Agent peer2) - { - for (String streamName : peer1.getStreamNames()) - { - IceMediaStream peer1Stream = peer1.getStream(streamName); - IceMediaStream peer2Stream = peer2.getStream(streamName); - if (peer1Stream == null || peer2Stream == null) - { - continue; - } - - for (Integer id : peer1Stream.getComponentIDs()) - { - Component peer1Component = peer1Stream.getComponent(id); - Component peer2Component = peer2Stream.getComponent(id); - if (peer1Component == null || peer2Component == null) - { - continue; - } - - copyRemoteCandidates(peer1Component, peer2Component); - copyRemoteCandidates(peer2Component, peer1Component); - } - } - } - - private static void copyRemoteCandidates(Component localComponent, - Component remoteComponent) - { - for(LocalCandidate candidate : remoteComponent.getLocalCandidates()) - { - localComponent.addRemoteCandidate( - new RemoteCandidate( - candidate.getTransportAddress(), - localComponent, - candidate.getType(), - candidate.getFoundation(), - candidate.getPriority(), - null)); - } - } -} +/* + * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. + * + * Copyright @ 2019 8x8, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.ice4j.ice; + +import static org.junit.jupiter.api.Assertions.*; + +import org.ice4j.*; + +import java.io.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.logging.*; +import org.junit.jupiter.api.*; + +/** + * RoleConflictResolutionTest set of tests which does end-to-end test + * of ICE role conflict recovery. + * + * @author Yura Yaroshevich + */ +public class RoleConflictResolutionTest +{ + protected static final Logger logger + = Logger.getLogger(RoleConflictResolutionTest.class.getName()); + + @Test + public void testRecoveryFromBothControlledConflict() + throws Throwable + { + testRecoveryFromRoleConflict(false); + } + + @Test + public void testRecoveryFromBothControllingConflict() + throws Throwable + { + testRecoveryFromRoleConflict(true); + } + + private static void testRecoveryFromRoleConflict(boolean bothControlling) + throws Throwable + { + final Agent peer1 = createPeer("[peer-1]", bothControlling); + // Set explicit tie-breakers to avoid automatic conflict resolution + peer1.setTieBreaker(1); + + final Agent peer2 = createPeer("[peer-2]", bothControlling); + peer1.setTieBreaker(2); + + final CountDownLatch countDownLatch = new CountDownLatch(2); + + for (Agent peer : Arrays.asList(peer1, peer2)) + { + peer.addStateChangeListener(evt -> + { + logger.info(peer.toString() + ": state changed to " + + evt.toString()); + if (peer.getState().isEstablished()) + { + countDownLatch.countDown(); + } + }); + } + + exchangeCredentials(peer1, peer2); + exchangeCandidates(peer1, peer2); + + peer1.startConnectivityEstablishment(); + peer2.startConnectivityEstablishment(); + + boolean isConnected = countDownLatch.await(20, TimeUnit.SECONDS); + + logSelectedPairs(peer1); + logSelectedPairs(peer2); + + assertTrue(isConnected, + "Expected connection established within time out"); + assertTrue(peer1.getState().isEstablished(), + "peer 1 connectivity"); + assertTrue(peer2.getState().isEstablished(), + "peer 2 connectivity"); + + disposePeer(peer1); + disposePeer(peer2); + } + + private static Agent createPeer(String label, boolean iceControlling) + throws IOException + { + final Agent agent = new Agent(label, null); + agent.setControlling(iceControlling); + IceMediaStream iceStream = agent.createMediaStream("media-stream"); + + agent.createComponent( + iceStream, + Transport.UDP, + 0x400, 0x400, 0xFFFF, + KeepAliveStrategy.ALL_SUCCEEDED, + true); + + return agent; + } + + private static void disposePeer(Agent peer) + { + peer.free(); + } + + private static void logSelectedPairs(Agent peer) + { + for (IceMediaStream stream : peer.getStreams()) + { + for (Component component : stream.getComponents()) + { + CandidatePair selectedPair = component.getSelectedPair(); + if (selectedPair != null) + { + logger.info( peer.toString() + ": selected pair for " + + "component " + component.getName() + " :" + + selectedPair.toString()); + } + } + } + } + + private static void exchangeCredentials(Agent peer1, Agent peer2) + { + for(IceMediaStream stream : peer2.getStreams()) + { + stream.setRemoteUfrag(peer1.getLocalUfrag()); + stream.setRemotePassword(peer1.getLocalPassword()); + } + + for(IceMediaStream stream : peer1.getStreams()) + { + stream.setRemoteUfrag(peer2.getLocalUfrag()); + stream.setRemotePassword(peer2.getLocalPassword()); + } + } + + private static void exchangeCandidates(Agent peer1, Agent peer2) + { + for (String streamName : peer1.getStreamNames()) + { + IceMediaStream peer1Stream = peer1.getStream(streamName); + IceMediaStream peer2Stream = peer2.getStream(streamName); + if (peer1Stream == null || peer2Stream == null) + { + continue; + } + + for (Integer id : peer1Stream.getComponentIDs()) + { + Component peer1Component = peer1Stream.getComponent(id); + Component peer2Component = peer2Stream.getComponent(id); + if (peer1Component == null || peer2Component == null) + { + continue; + } + + copyRemoteCandidates(peer1Component, peer2Component); + copyRemoteCandidates(peer2Component, peer1Component); + } + } + } + + private static void copyRemoteCandidates(Component localComponent, + Component remoteComponent) + { + for(LocalCandidate candidate : remoteComponent.getLocalCandidates()) + { + localComponent.addRemoteCandidate( + new RemoteCandidate( + candidate.getTransportAddress(), + localComponent, + candidate.getType(), + candidate.getFoundation(), + candidate.getPriority(), + null)); + } + } +} diff --git a/src/test/java/org/ice4j/ice/harvest/SinglePortUdpHarvesterTest.java b/src/test/java/org/ice4j/ice/harvest/SinglePortUdpHarvesterTest.java index ff7a863..2c11749 100644 --- a/src/test/java/org/ice4j/ice/harvest/SinglePortUdpHarvesterTest.java +++ b/src/test/java/org/ice4j/ice/harvest/SinglePortUdpHarvesterTest.java @@ -17,10 +17,12 @@ */ package org.ice4j.ice.harvest; +import static org.junit.jupiter.api.Assertions.*; + import org.ice4j.*; -import org.junit.*; import java.net.*; +import org.junit.jupiter.api.*; /** * Various tests that verify the functionality provided by {@link SinglePortUdpHarvester}. @@ -34,8 +36,8 @@ public class SinglePortUdpHarvesterTest * * @see https://github.com/jitsi/ice4j/issues/139 */ - @Test( expected = java.net.BindException.class ) - public void testRebindWithoutClose() throws Exception + @Test + public void testRebindWithoutCloseThrows() throws Exception { // Setup test fixture. final TransportAddress address = new TransportAddress( "127.0.0.1", 10000, Transport.UDP ); @@ -44,7 +46,7 @@ public class SinglePortUdpHarvesterTest { firstHarvester = new SinglePortUdpHarvester( address ); } - catch ( java.net.BindException ex ) + catch (BindException ex) { // This is not expected at this stage (the port is likely already in use by another process, voiding this // test). Rethrow as a different exception than the BindException, that is expected to be thrown later in @@ -57,14 +59,17 @@ public class SinglePortUdpHarvesterTest try { secondHarvester = new SinglePortUdpHarvester( address ); + fail("expected BindException to be thrown at this point"); + } + catch (BindException ex) + { + //expected, do nothing } - // Verification of the results is implicit - this Test expectes BindException to be thrown at this point. - - // Tear down finally { + // Tear down firstHarvester.close(); - if ( secondHarvester != null ) + if (secondHarvester != null) { secondHarvester.close(); } @@ -96,7 +101,7 @@ public class SinglePortUdpHarvesterTest // Verify results. catch ( BindException ex ) { - Assert.fail( "A bind exception should not have been thrown, as the original harvester was propertly closed."); + fail( "A bind exception should not have been thrown, as the original harvester was propertly closed."); } // Tear down. diff --git a/src/test/java/org/ice4j/message/MessageFactoryTest.java b/src/test/java/org/ice4j/message/MessageFactoryTest.java index 93c5860..49ea33f 100644 --- a/src/test/java/org/ice4j/message/MessageFactoryTest.java +++ b/src/test/java/org/ice4j/message/MessageFactoryTest.java @@ -17,36 +17,15 @@ */ package org.ice4j.message; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; import org.ice4j.attribute.*; +import org.junit.jupiter.api.*; -public class MessageFactoryTest extends TestCase +public class MessageFactoryTest { - private MsgFixture msgFixture; - - public MessageFactoryTest(String name) - { - super(name); - } - - protected void setUp() throws Exception - { - super.setUp(); - msgFixture = new MsgFixture(); - - msgFixture.setUp(); - } - - protected void tearDown() throws Exception - { - msgFixture.tearDown(); - - msgFixture = null; - super.tearDown(); - } - + @Test public void testCreateBindingErrorResponse() throws StunException { char errorCode = 400; @@ -60,10 +39,11 @@ public class MessageFactoryTest extends TestCase Message actualReturn = MessageFactory.createBindingErrorResponse(errorCode); - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } - public void testCreateBindingErrorResponse1() throws StunException + @Test + public void testCreateBindingErrorResponse1() { char errorCode = 400; String reasonPhrase = "Bad Request"; @@ -77,10 +57,10 @@ public class MessageFactoryTest extends TestCase Message actualReturn = MessageFactory .createBindingErrorResponse(errorCode, reasonPhrase); - assertEquals("Failed to create an error code attribute.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } + @Test public void testCreateBindingErrorResponseUnknownAttributes() throws StunException { @@ -91,17 +71,18 @@ public class MessageFactoryTest extends TestCase Response expectedReturn = new Response(); expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE); - Attribute errorCodeAtt = AttributeFactory + ErrorCodeAttribute errorCodeAtt = AttributeFactory .createErrorCodeAttribute(errorCode); - ((ErrorCodeAttribute)errorCodeAtt).setReasonPhrase( + errorCodeAtt.setReasonPhrase( ErrorCodeAttribute.getDefaultReasonPhrase(errorCode)); expectedReturn.putAttribute(errorCodeAtt); UnknownAttributesAttribute unknownAtts = AttributeFactory.createUnknownAttributesAttribute(); - for (int i = 0; i < unknownAttributes.length; i++) { - unknownAtts.addAttributeID(unknownAttributes[i]); + for (char unknownAttribute : unknownAttributes) + { + unknownAtts.addAttributeID(unknownAttribute); } expectedReturn.putAttribute(unknownAtts); @@ -109,9 +90,10 @@ public class MessageFactoryTest extends TestCase Message actualReturn = MessageFactory .createBindingErrorResponseUnknownAttributes(unknownAttributes); //compare - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } + @Test public void testCreateBindingErrorResponseUnknownAttributes1() throws StunException { @@ -129,22 +111,22 @@ public class MessageFactoryTest extends TestCase UnknownAttributesAttribute unknownAtts = AttributeFactory.createUnknownAttributesAttribute(); - for (int i = 0; i < unknownAttributes.length; i++) + for (char unknownAttribute : unknownAttributes) { - unknownAtts.addAttributeID(unknownAttributes[i]); + unknownAtts.addAttributeID(unknownAttribute); } expectedReturn.putAttribute(unknownAtts); Message actualReturn = MessageFactory .createBindingErrorResponseUnknownAttributes( reasonPhrase, unknownAttributes); - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn); } - public void testCreateBindingRequest() throws StunException + @Test + public void testCreateBindingRequest() { Request bindingRequest = new Request(); - Request expectedReturn = bindingRequest; bindingRequest.setMessageType(Message.BINDING_REQUEST); /* Attribute changeRequest = AttributeFactory.createChangeRequestAttribute( @@ -152,9 +134,10 @@ public class MessageFactoryTest extends TestCase bindingRequest.putAttribute(changeRequest); */ Request actualReturn = MessageFactory.createBindingRequest(); - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(bindingRequest, actualReturn); } + @Test public void testCreateBindingResponse() throws Exception { @@ -183,7 +166,6 @@ public class MessageFactoryTest extends TestCase bindingResponse.putAttribute(changedAddress); - Message expectedReturn = bindingResponse; Message actualReturn = MessageFactory.create3489BindingResponse( new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, MsgFixture.ADDRESS_ATTRIBUTE_PORT, @@ -194,6 +176,6 @@ public class MessageFactoryTest extends TestCase new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3, MsgFixture.ADDRESS_ATTRIBUTE_PORT_3, Transport.UDP)); - assertEquals("return value", expectedReturn, actualReturn); + assertEquals(bindingResponse, actualReturn); } } diff --git a/src/test/java/org/ice4j/message/MessageTest.java b/src/test/java/org/ice4j/message/MessageTest.java index b7c5fce..db05972 100644 --- a/src/test/java/org/ice4j/message/MessageTest.java +++ b/src/test/java/org/ice4j/message/MessageTest.java @@ -17,15 +17,14 @@ */ package org.ice4j.message; -import java.util.*; - -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; import org.ice4j.attribute.*; import org.ice4j.stack.*; +import org.junit.jupiter.api.*; -public class MessageTest extends TestCase +public class MessageTest { private Message bindingRequest = null; private Message bindingResponse = null; @@ -43,12 +42,12 @@ public class MessageTest extends TestCase */ private StunStack stunStack; - protected void setUp() throws Exception + @BeforeEach + public void setUp() throws Exception { - super.setUp(); - + System.clearProperty(StackProperties.ALWAYS_SIGN); + System.clearProperty(StackProperties.SOFTWARE); msgFixture = new MsgFixture(); - msgFixture.setUp(); stunStack = new StunStack(); @@ -89,7 +88,8 @@ public class MessageTest extends TestCase bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { bindingRequest = null; bindingResponse = null; @@ -97,48 +97,38 @@ public class MessageTest extends TestCase sourceAddress = null; changedAddress = null; changeRequest = null; - changeRequest = null; stunStack = null; - msgFixture.tearDown(); msgFixture = null; - - super.tearDown(); } /** * Adds and gets an attribute and test that they are the same then adds a - * another attribute (same typ different value) and veriies that the first + * another attribute (same typ different value) and verifies that the first * one is properly replaced. * - * @throws StunException java.lang.Exception if we fail */ - public void testAddAndGetAttribute() throws StunException + @Test + public void testAddAndGetAttribute() { - Response message = new Response(); message.setMessageType(Message.BINDING_SUCCESS_RESPONSE); message.putAttribute(mappedAddress); - Attribute getResult = null; - + Attribute getResult; getResult = message.getAttribute(mappedAddress.getAttributeType()); - assertEquals("Originally added attribute did not match the one retrned " - +"by getAttribute()", - mappedAddress, - getResult); + assertEquals(mappedAddress, getResult, + "Originally added attribute did not match the returned"); //do it again message.putAttribute(sourceAddress); getResult = message.getAttribute(sourceAddress.getAttributeType()); - - assertEquals("The second attribute could not be extracted.", - sourceAddress, - getResult); + assertEquals(sourceAddress, getResult, + "The second attribute could not be extracted."); } /** @@ -147,6 +137,7 @@ public class MessageTest extends TestCase * * @throws StunException java.lang.Exception if we fail */ + @Test public void testEncode() throws StunException { @@ -154,16 +145,16 @@ public class MessageTest extends TestCase byte[] expectedReturn = msgFixture.bindingRequest; byte[] actualReturn = bindingRequest.encode(stunStack); - assertTrue("A binding request was not properly encoded", - Arrays.equals( expectedReturn, actualReturn ) ); + assertArrayEquals(expectedReturn, actualReturn, + "A binding request was not properly encoded"); //Binding Response expectedReturn = msgFixture.bindingResponse; actualReturn = bindingResponse.encode(stunStack); - assertTrue("A binding response was not properly encoded", - Arrays.equals( expectedReturn, actualReturn ) ); + assertArrayEquals(expectedReturn, actualReturn, + "A binding response was not properly encoded"); } /** @@ -172,6 +163,7 @@ public class MessageTest extends TestCase * * @throws Exception java.lang.Exception if we fail */ + @Test public void testDecode() throws Exception { @@ -179,21 +171,21 @@ public class MessageTest extends TestCase Message expectedReturn = bindingRequest; Message actualReturn = Message.decode(msgFixture.bindingRequest, - (char)0, - (char)msgFixture.bindingRequest.length); + 0, + msgFixture.bindingRequest.length); - assertEquals("A binding request was not properly decoded", - expectedReturn, actualReturn ); + assertEquals(expectedReturn, actualReturn, + "A binding request was not properly decoded"); //Binding Response expectedReturn = bindingResponse; actualReturn = Message.decode(msgFixture.bindingResponse, - (char)0, - (char)msgFixture.bindingResponse.length); + 0, + msgFixture.bindingResponse.length); - assertEquals("A binding response was not properly decoded", - expectedReturn, actualReturn ); + assertEquals(expectedReturn, actualReturn, + "A binding response was not properly decoded"); } /** @@ -202,39 +194,30 @@ public class MessageTest extends TestCase * * @throws StunException java.lang.Exception if we fail */ + @Test public void testEquals() throws StunException { - Object target = null; - boolean expectedReturn = false; - boolean actualReturn = bindingRequest.equals(target); - assertEquals("Equals failed against a null target", - expectedReturn, actualReturn); + assertNotEquals(bindingRequest, null, + "Equals failed against a null target"); - actualReturn = bindingResponse.equals(target); - assertEquals("Equals failed against a null target", - expectedReturn, actualReturn); + assertNotEquals(bindingResponse, null, + "Equals failed against a null target"); //different - actualReturn = bindingRequest.equals(bindingResponse); - assertEquals("Equals failed against a different target", - expectedReturn, actualReturn); + assertNotEquals(bindingRequest, bindingResponse, + "Equals failed against a different target"); - actualReturn = bindingResponse.equals(bindingRequest); - assertEquals("Equals failed against a different target", - expectedReturn, actualReturn); - - //same - expectedReturn = true; + assertNotEquals(bindingResponse, bindingRequest, + "Equals failed against a different target"); //Create a binding request with the same attributes as //this.bindingRequest Request binReqTarget = new Request(); binReqTarget.setMessageType(Message.BINDING_REQUEST); binReqTarget.putAttribute(changeRequest); - actualReturn = bindingRequest.equals(binReqTarget); - assertEquals("Equals failed against an equal target", - expectedReturn, actualReturn); + assertEquals(bindingRequest, binReqTarget, + "Equals failed against an equal target"); //Create a binding response with the same attributes as //this.bindingRequest @@ -243,42 +226,42 @@ public class MessageTest extends TestCase binResTarget.putAttribute(mappedAddress); binResTarget.putAttribute(sourceAddress); binResTarget.putAttribute(changedAddress); - actualReturn = bindingResponse.equals(binResTarget); - assertEquals("Equals failed against a different target", - expectedReturn, actualReturn); + assertEquals(bindingResponse, binResTarget, + "Equals failed against a different target"); } /** * Tests whether attributes are properly counted */ + @Test public void testGetAttributeCount() { int expectedReturn = 1; int actualReturn = bindingRequest.getAttributeCount(); - assertEquals("getAttributeCount failed for a bindingRequest", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "getAttributeCount failed for a bindingRequest"); expectedReturn = 3; actualReturn = bindingResponse.getAttributeCount(); - assertEquals("getAttributeCount failed for a bindingRequest", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "getAttributeCount failed for a bindingRequest"); } /** * Test whether attributes are properly removed. */ + @Test public void testRemoveAttribute() { bindingRequest.removeAttribute(changeRequest.getAttributeType()); - assertNull("An attribute was still in the request after being removed", - bindingRequest.getAttribute(changeRequest.getAttributeType())); + assertNull(bindingRequest.getAttribute(changeRequest.getAttributeType()), + "An attribute was still in the request after being removed"); //test count int expectedReturn = 0; int actualReturn = bindingRequest.getAttributeCount(); - assertEquals( - "Attribute count did not change after removing an attribute", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "Attribute count did not change after removing an attribute"); } } diff --git a/src/test/java/org/ice4j/pseudotcp/MultiThreadSupportTest.java b/src/test/java/org/ice4j/pseudotcp/MultiThreadSupportTest.java index 4ebe225..8b7bddf 100755 --- a/src/test/java/org/ice4j/pseudotcp/MultiThreadSupportTest.java +++ b/src/test/java/org/ice4j/pseudotcp/MultiThreadSupportTest.java @@ -17,32 +17,26 @@ */ package org.ice4j.pseudotcp; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; /** - * This class enables multi thread tests where main thread waits in loop - * for specified condition to be met, while others perform some operations. - * For example until the connection is established or closed. - * It also registers default uncaught exception handler to catch exceptions - * from other threads. - * + * This class enables multi thread tests where main thread waits in loop for + * specified condition to be met, while others perform some operations. For + * example until the connection is established or closed. It also registers + * default uncaught exception handler to catch exceptions from other threads. + *

* Condition checks are passed as IWaitUntilDone interface. - * + * * @author Pawel Domas */ -public class MultiThreadSupportTest - extends TestCase - implements Thread.UncaughtExceptionHandler +public class MultiThreadSupportTest implements Thread.UncaughtExceptionHandler { private volatile Throwable testError; + private volatile Thread errorThread; - private final Object testLock = new Object(); - - public MultiThreadSupportTest() - { - - } - + + private final Object testLock = new Object(); + @Override public void uncaughtException(Thread t, Throwable e) { @@ -53,27 +47,30 @@ public class MultiThreadSupportTest testLock.notifyAll(); } } - - private long assertWaitInterval = 100; + + private static final long ASSERT_WAIT_INTERVAL = 100; + protected interface WaitUntilDone { - public boolean isDone(); - } - + boolean isDone(); + } + protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs) { try { long start = System.currentTimeMillis(); - while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs) + while (!wait.isDone() + && (System.currentTimeMillis() - start) < timeoutMs) { synchronized (testLock) { - testLock.wait(assertWaitInterval); + testLock.wait(ASSERT_WAIT_INTERVAL); if (testError != null) { testError.printStackTrace(); - fail("Error in thread: " + errorThread.getName() + " : " + testError.getMessage()); + fail("Error in thread: " + errorThread.getName() + " : " + + testError.getMessage()); } } } @@ -87,6 +84,4 @@ public class MultiThreadSupportTest return false; } } - - } diff --git a/src/test/java/org/ice4j/pseudotcp/PseudoTcpStreamTest.java b/src/test/java/org/ice4j/pseudotcp/PseudoTcpStreamTest.java index e7534fd..d553881 100755 --- a/src/test/java/org/ice4j/pseudotcp/PseudoTcpStreamTest.java +++ b/src/test/java/org/ice4j/pseudotcp/PseudoTcpStreamTest.java @@ -17,16 +17,13 @@ */ package org.ice4j.pseudotcp; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.*; import java.net.*; import java.util.logging.*; +import org.junit.jupiter.api.*; -/** - * - * @author Pawel Domas - */ public class PseudoTcpStreamTest extends MultiThreadSupportTest { @@ -36,14 +33,10 @@ public class PseudoTcpStreamTest private static final Logger logger = Logger .getLogger(PseudoTcpStreamTest.class.getName()); - public PseudoTcpStreamTest() - { - } - /** * Test one-way transfer with @link(PseudoTcpStream) - * @throws IOException */ + @Test public void testConnectTransferClose() throws IOException { @@ -69,7 +62,7 @@ public class PseudoTcpStreamTest public void run() { try - { + { server.setDebugName("L"); server.bind(serverAddress); server.accept(5000); @@ -94,7 +87,7 @@ public class PseudoTcpStreamTest } } }); - + final PseudoTcpSocket client = new PseudoTcpSocketFactory().createSocket(); Thread clientThread = new Thread(new Runnable() @@ -103,7 +96,7 @@ public class PseudoTcpStreamTest public void run() { try - { + { client.setDebugName("R"); client.connect(serverAddress, 5000); // write single array @@ -124,11 +117,10 @@ public class PseudoTcpStreamTest partsSize[i] = sizeB / partCount; } int written = 0; - for (int i = 0; i < partsSize.length; i++) + for (int j : partsSize) { - client.getOutputStream().write(bufferB, written, - partsSize[i]); - written += partsSize[i]; + client.getOutputStream().write(bufferB, written, j); + written += j; } assertEquals(sizeB, written); client.getOutputStream().flush(); @@ -191,35 +183,24 @@ public class PseudoTcpStreamTest /** * Test the timeout on accept method */ + @Test public void testAccept() { - try + assertThrows(IOException.class, ()-> { PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0); server.accept(10); - fail("Should throw timeout exception"); - } - catch (IOException ex) - { - // success - } + }); } - + /** * Interface used to pass timeout test function - * @author Pawel Domas - * */ private interface TimeoutOperationTest { void testTimeout(PseudoTcpSocketImpl socket) throws IOException; } - - /** - * - * @param testOperation - * @throws UnknownHostException - */ + private void doTestTimeout(final TimeoutOperationTest testOperation) throws Exception { @@ -234,7 +215,7 @@ public class PseudoTcpStreamTest client = new PseudoTcpSocketImpl(0); //Servers thread waiting for connection new Thread(new Runnable() - { + { @Override public void run() { @@ -255,7 +236,7 @@ public class PseudoTcpStreamTest { //success try - { + { server.close(); } catch (IOException exc) @@ -268,7 +249,6 @@ public class PseudoTcpStreamTest //Clients thread connects and closes socket new Thread(new Runnable() { - @Override public void run() { @@ -281,13 +261,12 @@ public class PseudoTcpStreamTest catch (Exception e) { throw new RuntimeException(e); - } + } } }).start(); //Waits for server to close socket boolean done = assert_wait_until(new WaitUntilDone() { - @Override public boolean isDone() { @@ -299,69 +278,55 @@ public class PseudoTcpStreamTest fail("Test timed out"); } } - + /** * Tests timeout on read method - * @throws UnknownHostException */ + @Test public void testReadTimeout() throws Exception { - doTestTimeout(new TimeoutOperationTest() + doTestTimeout(socket -> { - - @Override - public void testTimeout(PseudoTcpSocketImpl socket) throws IOException - { - socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300); - socket.getInputStream().read(new byte[500]); - } + socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300); + socket.getInputStream().read(new byte[500]); }); } - + /** * Tests timeout on write method - * @throws UnknownHostException */ + @Test public void testWriteTimeout() throws Exception { - doTestTimeout(new TimeoutOperationTest() - { - @Override - public void testTimeout(PseudoTcpSocketImpl socket) throws IOException - { - //buffer that will exceed stack's buffer size - byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2]; - socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300); - socket.getOutputStream().write(bigBuffer); - } + doTestTimeout(socket -> + { + //buffer that will exceed stack's buffer size + byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2]; + socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300); + socket.getOutputStream().write(bigBuffer); }); } - + /** * Tests timeout on flush method - * @throws UnknownHostException */ + @Test public void testFlushTimeout() throws Exception { - doTestTimeout(new TimeoutOperationTest() - { - @Override - public void testTimeout(PseudoTcpSocketImpl socket) throws IOException + doTestTimeout(socket -> + { + //buffer that will exceed stack's buffer size + byte[] buffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE]; + socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300); + try { - //buffer that will exceed stack's buffer size - byte[] buffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE]; - socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300); - try - { - socket.getOutputStream().write(buffer); - } - catch(IOException e) - { - throw new RuntimeException("Unexpected exception: "+e); - } - socket.getOutputStream().flush(); + socket.getOutputStream().write(buffer); } + catch(IOException e) + { + throw new RuntimeException("Unexpected exception: "+e); + } + socket.getOutputStream().flush(); }); } - } diff --git a/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestPingPong.java b/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestPingPong.java index 21f02bf..0baedf8 100755 --- a/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestPingPong.java +++ b/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestPingPong.java @@ -20,7 +20,10 @@ package org.ice4j.pseudotcp; import java.io.*; import java.util.logging.*; +import static org.junit.jupiter.api.Assertions.*; + import org.ice4j.pseudotcp.util.*; +import org.junit.jupiter.api.*; /** * This class implements test for two way transfers @@ -51,10 +54,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase */ private int iterationsRemaining; - public PseudoTcpTestPingPong() - { - } - public void setBytesPerSend(int bytes_per_send) { this.bytesPerSend = bytes_per_send; @@ -71,11 +70,8 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Performs ping-pong test for iterations with packets of * size bytes - * - * @param size - * @param iterations */ - public void doTestPingPong(int size, int iterations) + private void doTestPingPong(int size, int iterations) { Thread.setDefaultUncaughtExceptionHandler(this); long start; @@ -113,13 +109,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Catches onTcpReadable event for receiver - * - * @param tcp */ @Override public void onTcpReadable(PseudoTCPBase tcp) { - assertEquals("Unexpected onTcpReadable", receiver, tcp); + assertEquals(receiver, tcp, "Unexpected onTcpReadable"); try { // Stream bytes to the recv stream as they arrive. @@ -163,8 +157,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Catches the ontcpWriteable event for sender - * - * @param tcp */ @Override public void onTcpWriteable(PseudoTCPBase tcp) @@ -189,13 +181,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Reads the data in loop until is something available - * - * @throws IOException */ private void readData() throws IOException { byte[] block = new byte[kBlockSize]; - int rcvd = 0; + int rcvd; do { rcvd = receiver.recv(block, block.length); @@ -214,13 +204,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Writes all data to the receiver - * - * @throws IOException */ private void writeData() throws IOException { int tosend; - int sent = 0; + int sent; byte[] block = new byte[kBlockSize]; do { @@ -250,7 +238,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase while (sent > 0); } - /** + /* * * Ping-pong (request/response) tests * @@ -258,6 +246,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Test sending <= 1x MTU of data in each ping/pong. Should take <10ms. */ + @Test public void testPingPong1xMtu() { //logger.log(Level.INFO, "Test ping - pong 1xMTU"); @@ -270,6 +259,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase /** * Test sending 2x-3x MTU of data in each ping/pong. Should take <10ms. */ + @Test public void testPingPong3xMtu() { //logger.log(Level.INFO, "Test ping - pong 3xMTU"); @@ -283,6 +273,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase * Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to * interaction between Nagling and Delayed ACK. */ + @Test public void testPingPong2xMtu() { //logger.log(Level.INFO, "Test ping - pong 2xMTU"); @@ -296,6 +287,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase * Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off. * Should take <10ms. */ + @Test public void testPingPong2xMtuWithAckDelayOff() { //logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off"); @@ -310,6 +302,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase * Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should * take <10ms. */ + @Test public void testPingPong2xMtuWithNaglingOff() { //logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off"); @@ -324,6 +317,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase * Test sending a ping as pair of short (non-full) segments. Should take * ~1s, due to Delayed ACK interaction with Nagling. */ + @Test public void testPingPongShortSegments() { //logger.log(Level.INFO, "Test ping - pong short segments"); @@ -339,6 +333,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase * Test sending ping as a pair of short (non-full) segments, with Nagling * off. Should take <10ms. */ + @Test public void testPingPongShortSegmentsWithNaglingOff() { //logger.log(Level.INFO, "Test ping - pong short segments nagling off"); @@ -354,6 +349,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase * Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed * ACK. Should take ~1s. */ + @Test public void testPingPongShortSegmentsWithAckDelayOff() { //logger.log(Level.INFO, "Test ping - pong short segments nagling off"); diff --git a/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestRecvWindow.java b/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestRecvWindow.java index e1be1ed..cd0fdc4 100755 --- a/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestRecvWindow.java +++ b/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestRecvWindow.java @@ -21,7 +21,10 @@ import java.io.*; import java.util.*; import java.util.logging.*; +import static org.junit.jupiter.api.Assertions.*; + import org.ice4j.pseudotcp.util.*; +import org.junit.jupiter.api.*; /** * Fill the receiver window until it is full, drain it and then fill it with the @@ -62,7 +65,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase */ private int testDataSize; - public void doTestTransfer(int size) + private void doTestTransfer(int size) { Thread.setDefaultUncaughtExceptionHandler(this); testDataSize = size; @@ -94,15 +97,14 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase scheduleWriteAction(0); long transferTout = maxTransferTime(dummy.length, kMinTransferRate); - boolean transfferInTime = assert_Disconnected_wait(transferTout); + boolean transferInTime = assert_Disconnected_wait(transferTout); elapsed = PseudoTCPBase.now() - start; stopClocks(); int received = recv_stream.getBuffered(); - assertEquals("Transfer timeout, transferred: " + received + assertTrue(transferInTime, "Transfer timeout, transferred: " + received + " required: " + dummy.length + " elapsed: " - + elapsed + " limit: " + transferTout, - true, transfferInTime); + + elapsed + " limit: " + transferTout); assert 2 == send_position.size(); assert 2 == recv_position.size(); @@ -141,7 +143,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase * * - * @param scaleFactor * @return count bytes shadowed by scale actor */ static int getShadowedBytes(int scaleFactor) @@ -151,8 +152,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase /** * Reads all data available at the buffer - * - * @throws IOException */ void readUntilIOPending() throws IOException { @@ -186,8 +185,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase /** * Schedules write operation with delay given in ms - * - * @param delay */ void scheduleWriteAction(long delay) { @@ -212,8 +209,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase /** * Writes the data - * - * @throws IOException */ void writeData() throws IOException { @@ -336,6 +331,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase return getRemoteTcp().getM_rwnd_scale(); } + @Test public void testGetShadowedBytes() { assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0); @@ -350,6 +346,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase /** * Test that receive window expands and contract correctly. */ + @Test public void testReceiveWindow() { //logger.log(Level.INFO, "Test receive window"); @@ -364,6 +361,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase /** * Test setting send window size to a very small value. */ + @Test public void testSetVerySmallSendWindowSize() { //TODO: finish test @@ -381,6 +379,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase /** * Test setting receive window size to a value other than default. */ + @Test public void testSetReceiveWindowSize() { //logger.log(Level.INFO, "Test set receive window size"); diff --git a/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestTransfer.java b/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestTransfer.java index 4e5233b..232df67 100755 --- a/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestTransfer.java +++ b/src/test/java/org/ice4j/pseudotcp/PseudoTcpTestTransfer.java @@ -17,10 +17,11 @@ */ package org.ice4j.pseudotcp; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.*; import java.util.logging.*; +import org.junit.jupiter.api.*; /** * Implements one way transfer test @@ -35,10 +36,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase private static final Logger logger = Logger.getLogger(PseudoTCPBase.class.getName()); - public PseudoTcpTestTransfer() - { - super(); - } /** * The send data */ @@ -58,12 +55,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Transfers the data of size bytes - * - * @param size */ - public void doTestTransfer(int size) + private void doTestTransfer(int size) { - Thread.setDefaultUncaughtExceptionHandler(this); + Thread.setDefaultUncaughtExceptionHandler(this); long start, elapsed; int received; // Create some dummy data to send @@ -78,7 +73,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase try { connect(); - //assertEquals(0, Connect()); } catch (IOException ex) { @@ -89,15 +83,14 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase // Sending will start from OnTcpWriteable and complete when all data has // been received. long transferTout = maxTransferTime(sendData.length, kMinTransferRate); - boolean transfferInTime = assert_Disconnected_wait(transferTout); + boolean transferInTime = assert_Disconnected_wait(transferTout); elapsed = PseudoTCPBase.now() - start; stopClocks(); received = recvStream.size(); - assertEquals("Transfer timeout, transferred: " + received + assertTrue(transferInTime,"Transfer timeout, transferred: " + received + " required: " + sendData.length + " elapsed: " - + elapsed + " limit: " + transferTout, - true, transfferInTime); + + elapsed + " limit: " + transferTout); // Ensure we closed down OK and we got the right data. assertEquals(size, received); @@ -112,8 +105,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Reads all data available at remote peer's buffer - * - * @throws IOException */ void readData() throws IOException { @@ -135,7 +126,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Writes the data until there's space available * * @return true if there's no more data left to write - * @throws IOException */ boolean writeData() throws IOException { @@ -178,8 +168,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Catches TCP readable event for remote peer and reads the data. When total * read count equals send data size the test is finished. - * - * @param tcp */ @Override public void onTcpReadable(PseudoTCPBase tcp) @@ -215,8 +203,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Catches on TCP writeable event for local peer. Writes all data and closes * the stream - * - * @param tcp */ @Override public void onTcpWriteable(PseudoTCPBase tcp) @@ -245,6 +231,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Basic end-to-end data transfer tests Test the normal case of sending data * from one side to the other. */ + @Test public void testSend() { //logger.log(Level.INFO, "Test send"); @@ -258,6 +245,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Test sending data with a 50 ms RTT. Transmission should take longer due * to a slower ramp-up in send rate. */ + @Test public void testSendWithDelay() { //logger.log(Level.INFO, "Test send with delay"); @@ -272,6 +260,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Test sending data with packet loss. Transmission should take much longer * due to send back-off when loss occurs. */ + @Test public void testSendWithLoss() { //logger.log(Level.INFO, "Test send with loss"); @@ -287,6 +276,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * should take much longer due to send back-off and slower detection of * loss. */ + @Test public void testSendWithDelayAndLoss() { //logger.log(Level.INFO, "Test send with delay and loss"); @@ -302,6 +292,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Test sending data with 10% packet loss and Nagling disabled. Transmission * should take about the same time as with Nagling enabled. */ + @Test public void testSendWithLossAndOptNaglingOff() { //logger.log(Level.INFO, "Test send with loss and OptNagling off"); @@ -317,6 +308,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Test sending data with 10% packet loss and Delayed ACK disabled. * Transmission should be slightly faster than with it enabled. */ + @Test public void testSendWithLossAndOptAckDelayOff() { //logger.log(Level.INFO, "Test send with loss and OptAckDelay off"); @@ -331,6 +323,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test sending data with 50ms delay and Nagling disabled. */ + @Test public void testSendWithDelayAndOptNaglingOff() { //logger.log(Level.INFO, "Test send with delay and OptNagling off"); @@ -345,6 +338,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test sending data with 50ms delay and Delayed ACK disabled. */ + @Test public void testSendWithDelayAndOptAckDelayOff() { //logger.log(Level.INFO, "Test send with delay and OptAckDelay off"); @@ -359,6 +353,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test a large receive buffer with a sender that doesn't support scaling. */ + @Test public void testSendRemoteNoWindowScale() { //logger.log(Level.INFO, "Test send - remote no window scale"); @@ -374,6 +369,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase * Test a large sender-side receive buffer with a receiver that doesn't * support scaling. */ + @Test public void testSendLocalNoWindowScale() { //logger.log(Level.INFO, "Test send - local no window scale"); @@ -388,6 +384,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test when both sides use window scaling. */ + @Test public void testSendBothUseWindowScale() { //logger.log(Level.INFO, "Test send - both use window scale"); @@ -402,6 +399,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test using a large window scale value. */ + @Test public void testSendLargeInFlight() { //logger.log(Level.INFO, "Test send large in flight"); @@ -414,6 +412,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase test.doTestTransfer(1000000); } + @Test public void testSendBothUseLargeWindowScale() { //logger.log(Level.INFO, "Test send both use large window scale"); @@ -428,6 +427,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test using a small receive buffer. */ + @Test public void testSendSmallReceiveBuffer() { //logger.log(Level.INFO, "Test send small receive buffer"); @@ -442,6 +442,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase /** * Test using a very small receive buffer. */ + @Test public void testSendVerySmallReceiveBuffer() { //logger.log(Level.INFO, "Test send very small receive buffer"); diff --git a/src/test/java/org/ice4j/pseudotcp/util/ByteFifoBufferTest.java b/src/test/java/org/ice4j/pseudotcp/util/ByteFifoBufferTest.java index 1dd337b..b48460e 100755 --- a/src/test/java/org/ice4j/pseudotcp/util/ByteFifoBufferTest.java +++ b/src/test/java/org/ice4j/pseudotcp/util/ByteFifoBufferTest.java @@ -17,19 +17,18 @@ */ package org.ice4j.pseudotcp.util; -import static org.junit.Assert.*; - import java.nio.*; import java.util.*; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.*; /** * * @author Pawel Domas */ public class ByteFifoBufferTest - extends TestCase { public ByteFifoBufferTest() { @@ -38,6 +37,7 @@ public class ByteFifoBufferTest /** * Test of Length method, of class ByteFifoBuffer. */ + @Test public void testLength() { int expResult = 1000; @@ -52,6 +52,7 @@ public class ByteFifoBufferTest /** * Test of Read method, of class ByteFifoBuffer. */ + @Test public void testRead() { int count = 1024; @@ -60,9 +61,8 @@ public class ByteFifoBufferTest instance.write(wData, count); byte[] readBuff = new byte[count]; - int expResult = count; int result = instance.read(readBuff, count); - assertEquals(expResult, result); + assertEquals(count, result); assertArrayEquals(wData, readBuff); } @@ -70,6 +70,7 @@ public class ByteFifoBufferTest /** * Tests reading with an offset for destination buffer */ + @Test public void testReadWithOffset() { int count = 1024; @@ -93,7 +94,6 @@ public class ByteFifoBufferTest * return some random array * * @param count array size - * @return */ private byte[] getWData(int count) { @@ -106,6 +106,7 @@ public class ByteFifoBufferTest /** * Test of GetWriteRemaining method, of class ByteFifoBuffer. */ + @Test public void testGetWriteRemaining() { int len = 100; @@ -126,6 +127,7 @@ public class ByteFifoBufferTest /** * Test of GetBuffered method, of class ByteFifoBuffer. */ + @Test public void testGetBuffered() { int len = 1000; @@ -148,14 +150,14 @@ public class ByteFifoBufferTest /** * Test of Write method, of class ByteFifoBuffer. */ + @Test public void testWrite() { int len = 2048; byte[] data = getWData(len); ByteFifoBuffer instance = new ByteFifoBuffer(len); - int expResult = len; int result = instance.write(data, len); - assertEquals(expResult, result); + assertEquals(len, result); byte[] read = new byte[len]; int readCount = instance.read(read, len); @@ -163,6 +165,7 @@ public class ByteFifoBufferTest assertArrayEquals(data, read); } + @Test public void testWriteWithOffset() { int len = 2048; @@ -183,6 +186,7 @@ public class ByteFifoBufferTest /** * Test of ConsumeWriteBuffer method, of class ByteFifoBuffer. */ + @Test public void testConsumeWriteBuffer() { int len = 100; @@ -208,6 +212,7 @@ public class ByteFifoBufferTest /** * Test of SetCapacity method, of class ByteFifoBuffer. */ + @Test public void testSetCapacity() { int old_size = 100; @@ -229,6 +234,7 @@ public class ByteFifoBufferTest /** * Test of ConsumeReadData method, of class ByteFifoBuffer. */ + @Test public void testConsumeReadData() { int lCount = 100; @@ -250,6 +256,7 @@ public class ByteFifoBufferTest /** * Test of ReadOffset method, of class ByteFifoBuffer. */ + @Test public void testReadOffset() { int dst_buff_offset = 0; @@ -258,11 +265,10 @@ public class ByteFifoBufferTest byte[] dst_buff = new byte[len]; int offset = 0; ByteFifoBuffer instance = new ByteFifoBuffer(len); - int expResult = len; instance.write(src_buff, len); int result = instance.readOffset(dst_buff, dst_buff_offset, len, offset); - assertEquals(expResult, result); + assertEquals(len, result); assertArrayEquals(dst_buff, src_buff); } @@ -270,6 +276,7 @@ public class ByteFifoBufferTest /** * Test of WriteOffset method, of class ByteFifoBuffer. */ + @Test public void testWriteOffset() { int len = 200; @@ -301,6 +308,7 @@ public class ByteFifoBufferTest } + @Test public void testWriteReadWriteRead() { int len = 2000; @@ -330,6 +338,7 @@ public class ByteFifoBufferTest while ((read != wrData.length) || (written != wrData.length)); } + @Test public void testSomeMultiTest() { int Alen = 16; diff --git a/src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java b/src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java new file mode 100644 index 0000000..809cbc0 --- /dev/null +++ b/src/test/java/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java @@ -0,0 +1,32 @@ +package org.ice4j.socket.jdk8; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; + +import org.junit.jupiter.api.*; + +public class MuxServerSocketChannelTest +{ + @Disabled + @Test + void testOpenAndBindReuseWhenBindingToAllInterfacesFirst() + throws IOException + { + SocketAddress allInterfaces = new InetSocketAddress("::", 4443); + SocketAddress oneInterface = new InetSocketAddress("localhost", 4443); + + MuxServerSocketChannel channelForAllInterfaces = + MuxServerSocketChannel + .openAndBind(null, allInterfaces, 0, p -> false); + + MuxServerSocketChannel channelForOneInterface = + MuxServerSocketChannel + .openAndBind(null, oneInterface, 0, p -> false); + + assertEquals(channelForAllInterfaces.getFDVal(), + channelForOneInterface.getFDVal()); + } +} diff --git a/src/test/java/org/ice4j/stack/ShallowStackTest.java b/src/test/java/org/ice4j/stack/ShallowStackTest.java index 254d3ac..2185257 100644 --- a/src/test/java/org/ice4j/stack/ShallowStackTest.java +++ b/src/test/java/org/ice4j/stack/ShallowStackTest.java @@ -18,21 +18,21 @@ package org.ice4j.stack; import java.net.*; -import java.util.*; import java.util.logging.*; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; import org.ice4j.message.*; import org.ice4j.socket.*; +import org.junit.jupiter.api.*; /** * All unit stack tests should be provided later. I just don't have the time now. * * @author Emil Ivov */ -public class ShallowStackTest extends TestCase +public class ShallowStackTest { /** * The Logger used by the ShallowStackTest class and its @@ -56,44 +56,34 @@ public class ShallowStackTest extends TestCase private DatagramSocket dummyServerSocket = null; - /** - * Creates a test instance for the method with the specified name. - * - * @param name the name of the test we'd like to create an instance for. - */ - public ShallowStackTest(String name) - { - super(name); - } - /** * Initializes whatever sockets we'll be using in our tests. * * @throws Exception if something goes wrong with socket initialization. */ - protected void setUp() + @BeforeEach + public void setUp() throws Exception { - super.setUp(); + System.clearProperty(StackProperties.ALWAYS_SIGN); + System.clearProperty(StackProperties.SOFTWARE); msgFixture = new MsgFixture(); - msgFixture.setUp(); - //Addresses - dummyServerAddress = new TransportAddress( - "127.0.0.1", 6004, Transport.UDP); - localAddress = new TransportAddress( - "127.0.0.1", 5004, Transport.UDP); //init the stack stunStack = new StunStack(); //access point localSock = new IceUdpSocketWrapper( - new SafeCloseDatagramSocket(localAddress)); + new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0))); + localAddress = new TransportAddress( + "127.0.0.1", localSock.getLocalPort(), Transport.UDP); stunStack.addSocket(localSock); //init the dummy server - dummyServerSocket = new DatagramSocket( dummyServerAddress ); + dummyServerSocket = new DatagramSocket(new InetSocketAddress("127.0.0.1", 0)); + dummyServerAddress = new TransportAddress( + "127.0.0.1", dummyServerSocket.getLocalPort(), Transport.UDP); } /** @@ -101,18 +91,18 @@ public class ShallowStackTest extends TestCase * * @throws Exception if closing the sockets fails. */ - protected void tearDown() + @AfterEach + public void tearDown() throws Exception { stunStack.removeSocket(localAddress); + stunStack.shutDown(); localSock.close(); dummyServerSocket.close(); - msgFixture.tearDown(); msgFixture = null; - super.tearDown(); } @@ -123,6 +113,7 @@ public class ShallowStackTest extends TestCase * * @throws java.lang.Exception if we fail */ + @Test public void testSendRequest() throws Exception { @@ -140,17 +131,15 @@ public class ShallowStackTest extends TestCase DatagramPacket receivedPacket = dgramCollector.collectPacket(); - assertTrue("The stack did not properly send a Binding Request", - (receivedPacket.getLength() > 0)); + assertTrue((receivedPacket.getLength() > 0), + "The stack did not properly send a Binding Request"); Request receivedRequest = (Request)Request.decode(receivedPacket.getData(), (char)0, (char)receivedPacket.getLength()); - assertEquals("The received request did not match the " - +"one that was sent.", - bindingRequest, //expected - receivedRequest); // actual + assertEquals(bindingRequest, receivedRequest, + "The received request did not match the one that was sent."); //wait for retransmissions @@ -160,16 +149,15 @@ public class ShallowStackTest extends TestCase receivedPacket = dgramCollector.collectPacket(); - assertTrue("The stack did not retransmit a Binding Request", - (receivedPacket.getLength() > 0)); + assertTrue((receivedPacket.getLength() > 0), + "The stack did not retransmit a Binding Request"); receivedRequest = (Request)Request.decode( receivedPacket.getData(), - (char)0, - (char)receivedPacket.getLength()); - assertEquals("The retransmitted request did not match the original.", - bindingRequest, //expected - receivedRequest); // actual + 0, + receivedPacket.getLength()); + assertEquals(bindingRequest, receivedRequest, + "The retransmitted request did not match the original."); } /** @@ -178,6 +166,7 @@ public class ShallowStackTest extends TestCase * * @throws java.lang.Exception if we fail */ + @Test public void testReceiveRequest() throws Exception { @@ -194,12 +183,12 @@ public class ShallowStackTest extends TestCase Request collectedRequest = requestCollector.collectedRequest; - assertNotNull("No request has been received", collectedRequest); + assertNotNull(collectedRequest, "No request has been received"); - byte expectedReturn[] = msgFixture.bindingRequest2; - byte actualReturn[] = collectedRequest.encode(stunStack); - assertTrue("Received request was not the same as the one that was sent", - Arrays.equals(expectedReturn, actualReturn)); + byte[] expectedReturn = msgFixture.bindingRequest2; + byte[] actualReturn = collectedRequest.encode(stunStack); + assertArrayEquals(expectedReturn, actualReturn, + "Received request was not the same as the one that was sent"); } /** @@ -210,6 +199,7 @@ public class ShallowStackTest extends TestCase * * @throws java.lang.Exception if we fail */ + @Test public void testSendResponse() throws Exception { @@ -227,10 +217,10 @@ public class ShallowStackTest extends TestCase Request collectedRequest = requestCollector.collectedRequest; - byte expectedReturn[] = msgFixture.bindingRequest; - byte actualReturn[] = collectedRequest.encode(stunStack); - assertTrue("Received request was not the same as the one that was sent", - Arrays.equals(expectedReturn, actualReturn)); + byte[] expectedReturn = msgFixture.bindingRequest; + byte[] actualReturn = collectedRequest.encode(stunStack); + assertArrayEquals(expectedReturn, actualReturn, + "Received request was not the same as the one that was sent"); //---------- create the response --------------------------------------- Response bindingResponse = MessageFactory.create3489BindingResponse( @@ -254,17 +244,15 @@ public class ShallowStackTest extends TestCase DatagramPacket receivedPacket = dgramCollector.collectPacket(); - assertTrue("The stack did not properly send a Binding Request", - (receivedPacket.getLength() > 0)); + assertTrue((receivedPacket.getLength() > 0), + "The stack did not properly send a Binding Request"); Response receivedResponse = (Response) Response.decode(receivedPacket.getData(), - (char) 0, - (char) receivedPacket.getLength()); - assertEquals( - "The received request did not match the one that was sent.", - bindingResponse, //expected - receivedResponse); // actual + 0, + receivedPacket.getLength()); + assertEquals(bindingResponse, receivedResponse, + "The received request did not match the one that was sent."); } /** @@ -272,6 +260,7 @@ public class ShallowStackTest extends TestCase * * @throws Exception if something fails somewhere. */ + @Test public void testReceiveResponse() throws Exception { @@ -288,7 +277,7 @@ public class ShallowStackTest extends TestCase collector.waitForResponse(); //create the right response - byte response[] = new byte[msgFixture.bindingResponse.length]; + byte[] response = new byte[msgFixture.bindingResponse.length]; System.arraycopy(msgFixture.bindingResponse, 0, response, 0, response.length); @@ -310,15 +299,15 @@ public class ShallowStackTest extends TestCase Response collectedResponse = collector.collectedResponse; - byte expectedReturn[] = response; - byte actualReturn[] = collectedResponse.encode(stunStack); - assertTrue("Received request was not the same as the one that was sent", - Arrays.equals(expectedReturn, actualReturn)); + byte[] actualReturn = collectedResponse.encode(stunStack); + assertArrayEquals(response, actualReturn, + "Received request was not the same as the one that was sent"); } /** * Verify StackProperties.FIRST_CTRAN_RETRANS_AFTER can indeed update StunClientTransaction.Retransmitter */ + @Test public void testRetransmissionOriginalWait() throws Exception { @@ -340,39 +329,36 @@ public class ShallowStackTest extends TestCase dgramCollector.waitForPacket(); DatagramPacket receivedPacket = dgramCollector.collectPacket(); - assertTrue("The stack did not properly send a Binding Request", - (receivedPacket.getLength() > 0)); + assertTrue((receivedPacket.getLength() > 0), + "The stack did not properly send a Binding Request"); Request receivedRequest = (Request)Request.decode(receivedPacket.getData(), (char)0, (char)receivedPacket.getLength()); - assertEquals("The received request did not match the " - +"one that was sent.", - bindingRequest, //expected - receivedRequest); // actual + assertEquals(bindingRequest, receivedRequest, + "The received request did not match the one that was sent."); // wait for the 1st retransmission with originalWait dgramCollector.startListening(dummyServerSocket); dgramCollector.waitForPacket(); receivedPacket = dgramCollector.collectPacket(); - assertTrue("The stack did not retransmit a Binding Request", - (receivedPacket.getLength() > 0)); + assertTrue((receivedPacket.getLength() > 0), + "The stack did not retransmit a Binding Request"); - receivedRequest = (Request)Request.decode( - receivedPacket.getData(), - (char)0, - (char)receivedPacket.getLength()); - assertEquals("The retransmitted request did not match the original.", - bindingRequest, //expected - receivedRequest); // actual + receivedRequest = (Request) Request.decode( + receivedPacket.getData(), + 0, + receivedPacket.getLength()); + assertEquals(bindingRequest, receivedRequest, + "The retransmitted request did not match the original."); // verify the retransmission is longer than the originalWait long secondTime = System.currentTimeMillis(); - assertTrue((secondTime - firstTime) >= originalWait); + assertTrue((secondTime - firstTime) >= originalWait); - System.clearProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER); + System.clearProperty(StackProperties.FIRST_CTRAN_RETRANS_AFTER); } //--------------------------------------- listener implementations --------- diff --git a/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest.java b/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest.java index c94f01b..acf8490 100644 --- a/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest.java +++ b/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest.java @@ -17,12 +17,12 @@ */ package org.ice4j.stunclient; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; import org.ice4j.message.*; import org.ice4j.stack.*; - +import org.junit.jupiter.api.*; /** * The StunAddressDiscovererTest_XXX set of tests were created to verify stun * operation for scenarios of some basic types of firewalls. The purpose of @@ -34,32 +34,24 @@ import org.ice4j.stack.*; * @author Emil Ivov */ public class StunAddressDiscovererTest - extends TestCase { private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null; - private TransportAddress discovererAddress + private final TransportAddress discovererAddress = new TransportAddress("127.0.0.1", 15555, Transport.UDP); private ResponseSequenceServer responseServer = null; - private TransportAddress responseServerAddress + private final TransportAddress responseServerAddress = new TransportAddress("127.0.0.1", 19999, Transport.UDP); - private TransportAddress mappedClientAddress + private final TransportAddress mappedClientAddress = new TransportAddress("212.56.4.10", 15612, Transport.UDP); - private TransportAddress mappedClientAddressPort2 + private final TransportAddress mappedClientAddressPort2 = new TransportAddress("212.56.4.10", 15611, Transport.UDP); - public StunAddressDiscovererTest(String name) - throws StunException + @BeforeEach + public void setUp() throws Exception { - super(name); - } - - protected void setUp() throws Exception - { - super.setUp(); - System.setProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER, "100"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); @@ -76,15 +68,14 @@ public class StunAddressDiscovererTest responseServer.start(); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); responseServer.shutDown(); stunAddressDiscoverer.shutDown(); stunAddressDiscoverer = null; - - super.tearDown(); } /** @@ -93,6 +84,7 @@ public class StunAddressDiscovererTest * * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeBlockedUDP() throws Exception { @@ -104,10 +96,8 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer .determineAddress(); - assertEquals("The StunAddressDiscoverer failed for a " - +"no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } @@ -116,6 +106,7 @@ public class StunAddressDiscovererTest * it concludes it is behind a Symmetric NAT. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeSymmetricNat() throws Exception { //define the server response sequence @@ -139,10 +130,8 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer.determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, - actualReturn); + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } @@ -151,6 +140,7 @@ public class StunAddressDiscovererTest * it concludes it is behind a Port Restricted Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizePortRestrictedCone() throws Exception { @@ -175,8 +165,8 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer.determineAddress(); - assertEquals("The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } @@ -185,6 +175,7 @@ public class StunAddressDiscovererTest * it concludes it is behind a Restricted Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeRestrictedCone() throws Exception { //define the server response sequence @@ -208,10 +199,8 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer .determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -219,6 +208,7 @@ public class StunAddressDiscovererTest * it concludes it is behind a Full Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeFullCone() throws Exception { @@ -238,9 +228,8 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer. determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -249,6 +238,7 @@ public class StunAddressDiscovererTest * * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeUdpSymmetricFirewall() throws Exception { @@ -267,9 +257,8 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer. determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } @@ -279,6 +268,7 @@ public class StunAddressDiscovererTest * * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeOpenInternet() throws Exception { @@ -298,8 +288,7 @@ public class StunAddressDiscovererTest StunDiscoveryReport actualReturn = stunAddressDiscoverer. determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } } diff --git a/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java b/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java index e1f3683..6e4bd64 100644 --- a/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java +++ b/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v4v6.java @@ -17,12 +17,12 @@ */ package org.ice4j.stunclient; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; import org.ice4j.message.*; import org.ice4j.stack.*; - +import org.junit.jupiter.api.*; /** * Makes basic stun tests for cases where local network addresses and the public * NAT address are using different IP versions. (e.g. Local addresses are v4 @@ -38,48 +38,41 @@ import org.ice4j.stack.*; *

Company: Net Research Team, Louis Pasteur University

* @author Emil Ivov */ -public class StunAddressDiscovererTest_v4v6 extends TestCase +public class StunAddressDiscovererTest_v4v6 { private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v6 = null; private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v4 = null; - private TransportAddress discovererAddress_v4 + private final TransportAddress discovererAddress_v4 = new TransportAddress("127.0.0.1", 17555, Transport.UDP); - private TransportAddress discovererAddress_v6 + private final TransportAddress discovererAddress_v6 = new TransportAddress("::1", 17555, Transport.UDP); private ResponseSequenceServer responseServer_v6 = null; private ResponseSequenceServer responseServer_v4 = null; - private TransportAddress responseServerAddress_v6 + private final TransportAddress responseServerAddress_v6 = new TransportAddress("::1", 21999, Transport.UDP); - private TransportAddress responseServerAddress_v4 + private final TransportAddress responseServerAddress_v4 = new TransportAddress("127.0.0.1", 21999, Transport.UDP); - private TransportAddress mappedClientAddress_v6 = new TransportAddress( + private final TransportAddress mappedClientAddress_v6 = new TransportAddress( "2001:660:4701:1001:ff::1", 17612, Transport.UDP); - private TransportAddress mappedClientAddress_v6_Port2 + private final TransportAddress mappedClientAddress_v6_Port2 = new TransportAddress( "2001:660:4701:1001:ff::1", 17611, Transport.UDP); - private TransportAddress mappedClientAddress_v4 + private final TransportAddress mappedClientAddress_v4 = new TransportAddress("130.79.99.55", 17612, Transport.UDP); - private TransportAddress mappedClientAddress_v4_Port2 + private final TransportAddress mappedClientAddress_v4_Port2 = new TransportAddress("130.79.99.55", 17611, Transport.UDP); - public StunAddressDiscovererTest_v4v6(String name) - throws StunException - { - super(name); - } - - protected void setUp() + @BeforeEach + public void setUp() throws Exception { - super.setUp(); - StunStack stunStack = new StunStack(); responseServer_v6 @@ -105,7 +98,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); } - protected void tearDown() + @AfterEach + public void tearDown() throws Exception { System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); @@ -120,8 +114,6 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase //give the sockets the time to clear out Thread.sleep(1000); - - super.tearDown(); } /** @@ -129,6 +121,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase * it concludes it is behind a Symmetric NAT. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeSymmetricNat_Local_v6_Public_v4() throws Exception { @@ -155,9 +148,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6.determineAddress(); - assertEquals("The StunAddressDiscoverer failed for a v4-v6 sym env.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a v4-v6 sym env."); } /** @@ -165,6 +157,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase * it concludes it is behind a Symmetric NAT. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeSymmetricNat_Local_v4_Public_v6() throws Exception { //define the server response sequence @@ -190,11 +183,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4.determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, - actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -202,6 +192,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase * it concludes it is behind a Full Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeFullCone_Local_v6_Public_v4() throws Exception { //define the server response sequence @@ -224,10 +215,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6. determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -235,6 +224,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase * it concludes it is behind a Full Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeFullCone_Local_v4_Public_v6() throws Exception { //define the server response sequence @@ -257,9 +247,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4. determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } } diff --git a/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java b/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java index c5d7678..cfd3060 100644 --- a/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java +++ b/src/test/java/org/ice4j/stunclient/StunAddressDiscovererTest_v6.java @@ -17,11 +17,12 @@ */ package org.ice4j.stunclient; -import junit.framework.*; +import static org.junit.jupiter.api.Assertions.*; import org.ice4j.*; import org.ice4j.message.*; import org.ice4j.stack.*; +import org.junit.jupiter.api.*; /** * The StunAddressDiscovererTest_XXX set of tests were created to verify stun @@ -33,31 +34,24 @@ import org.ice4j.stack.*; *

Company: Net Research Team, Louis Pasteur University

* @author Emil Ivov */ -public class StunAddressDiscovererTest_v6 extends TestCase +public class StunAddressDiscovererTest_v6 { private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null; - private TransportAddress discovererAddress + private final TransportAddress discovererAddress = new TransportAddress("::1", 16555, Transport.UDP); private ResponseSequenceServer responseServer = null; - private TransportAddress responseServerAddress + private final TransportAddress responseServerAddress = new TransportAddress("::1", 20999, Transport.UDP); - private TransportAddress mappedClientAddress = new TransportAddress( + private final TransportAddress mappedClientAddress = new TransportAddress( "2001:660:4701:1001:ff::1", 16612, Transport.UDP); - private TransportAddress mappedClientAddressPort2 = new TransportAddress( + private final TransportAddress mappedClientAddressPort2 = new TransportAddress( "2001:660:4701:1001:ff::1", 16611, Transport.UDP); - public StunAddressDiscovererTest_v6(String name) - throws StunException + @BeforeEach + public void setUp() throws Exception { - super(name); - } - - protected void setUp() throws Exception - { - super.setUp(); - StunStack stunStack = new StunStack(); responseServer @@ -74,15 +68,14 @@ public class StunAddressDiscovererTest_v6 extends TestCase System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); } - protected void tearDown() throws Exception + @AfterEach + public void tearDown() throws Exception { System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); responseServer.shutDown(); stunAddressDiscoverer.shutDown(); stunAddressDiscoverer = null; - - super.tearDown(); } /** @@ -90,6 +83,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase * it concludes it's in a network where UDP is blocked. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeBlockedUDP() throws Exception { @@ -101,20 +95,17 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer.determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, - actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } - /** * Performs a test where no responces are given the stun client so that * it concludes it is behind a Symmetric NAT. * * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeSymmetricNat() throws Exception { @@ -139,10 +130,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer.determineAddress(); - assertEquals("The StunAddressDiscoverer failed for a " - +"no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -150,6 +139,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase * it concludes it is behind a Port Restricted Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizePortRestrictedCone() throws Exception { @@ -174,10 +164,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer.determineAddress(); - assertEquals("The StunAddressDiscoverer failed for" - +" a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -185,6 +173,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase * it concludes it is behind a Restricted Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeRestrictedCone() throws Exception { @@ -209,10 +198,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer.determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -220,6 +207,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase * it concludes it is behind a Full Cone. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeFullCone() throws Exception { //define the server response sequence @@ -238,10 +226,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer .determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -249,6 +235,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase * it concludes it is behind a UDP Symmetric Firewall. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeUdpSymmetricFirewall() throws Exception { @@ -267,10 +254,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer .determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } /** @@ -278,6 +263,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase * it concludes it is behind a Open Internet. * @throws Exception if anything goes wrong ( surprised? ). */ + @Test public void testRecognizeOpenInternet() throws Exception { @@ -297,9 +283,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase StunDiscoveryReport actualReturn = stunAddressDiscoverer. determineAddress(); - assertEquals( - "The StunAddressDiscoverer failed for a no-udp environment.", - expectedReturn, actualReturn); - + assertEquals(expectedReturn, actualReturn, + "The StunAddressDiscoverer failed for a no-udp environment."); } } diff --git a/src/test/java/org/ice4j/util/PeriodicRunnableTests.java b/src/test/java/org/ice4j/util/PeriodicRunnableTests.java index 65e61cd..446f19e 100644 --- a/src/test/java/org/ice4j/util/PeriodicRunnableTests.java +++ b/src/test/java/org/ice4j/util/PeriodicRunnableTests.java @@ -1,9 +1,12 @@ package org.ice4j.util; -import org.junit.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; import java.time.*; import java.util.concurrent.*; +import org.jitsi.test.concurrent.*; +import org.junit.jupiter.api.*; /** * Test various aspects of {@link PeriodicRunnable} implementation. @@ -12,39 +15,52 @@ import java.util.concurrent.*; */ public class PeriodicRunnableTests { + private FakeScheduledExecutorService timer; + private ExecutorService executor; + + @BeforeEach + void beforeEach() + { + timer = mock( + FakeScheduledExecutorService.class, + withSettings() + .useConstructor() + .defaultAnswer(CALLS_REAL_METHODS) + ); + executor = mock(ExecutorService.class); + when(executor.submit(any(Runnable.class))).thenAnswer(a -> + { + ((Runnable)a.getArgument(0)).run(); + return CompletableFuture.completedFuture(null); + }); + } + @Test public void scheduleExecutesSpecifiedRunnableMultipleTimes() - throws InterruptedException { - final ScheduledExecutorService timer - = Executors.newSingleThreadScheduledExecutor(); - final ExecutorService executor = Executors.newSingleThreadExecutor(); - final CountDownLatch latch = new CountDownLatch(10); + int scheduleCount = 10; + Duration period = Duration.ofMillis(100); + final CountDownLatch latch = new CountDownLatch(scheduleCount); final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( timer, executor, - Duration.ofMillis(100), + period, latch::countDown); scheduledRunnable.schedule(); - // Give 20 extra milliseconds to avoid possible failures due to - // slight timer inaccuracy - latch.await(1020, TimeUnit.MILLISECONDS); - Assert.assertEquals(0, latch.getCount()); + for (int i = 0; i < scheduleCount; i++) + { + timer.getClock().elapse(period.plusMillis(10)); + timer.run(); + } - scheduledRunnable.cancel(); - executor.shutdownNow(); - timer.shutdownNow(); + assertEquals(0, latch.getCount()); } @Test public void scheduleWithNegativeDelayDoesNotExecuteRunnable() - throws InterruptedException { - final ScheduledExecutorService timer - = Executors.newSingleThreadScheduledExecutor(); - final ExecutorService executor = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(1); final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( timer, @@ -54,22 +70,16 @@ public class PeriodicRunnableTests scheduledRunnable.schedule(); - latch.await(1000, TimeUnit.MILLISECONDS); - Assert.assertEquals(1, latch.getCount()); - - scheduledRunnable.cancel(); - executor.shutdownNow(); - timer.shutdownNow(); + timer.getClock().elapse(Duration.ofSeconds(1)); + timer.run(); + assertEquals(1, latch.getCount()); } @Test public void negativeDelayStopsFurtherExecution() - throws InterruptedException { - final ScheduledExecutorService timer - = Executors.newSingleThreadScheduledExecutor(); - final ExecutorService executor = Executors.newSingleThreadExecutor(); - final CountDownLatch latch = new CountDownLatch(5); + int scheduleCount = 5; + final CountDownLatch latch = new CountDownLatch(scheduleCount); final PeriodicRunnable scheduledRunnable = new PeriodicRunnable(timer, executor) { @@ -88,21 +98,18 @@ public class PeriodicRunnableTests scheduledRunnable.schedule(); - latch.await(1000, TimeUnit.MILLISECONDS); - Assert.assertEquals(1, latch.getCount()); + for (int i = 0; i < scheduleCount; i++) + { + timer.getClock().elapse(Duration.ofMillis(100)); + timer.run(); + } - scheduledRunnable.cancel(); - executor.shutdownNow(); - timer.shutdownNow(); + assertEquals(1, latch.getCount()); } @Test public void cancelStopFurtherExecution() - throws InterruptedException { - final ScheduledExecutorService timer - = Executors.newSingleThreadScheduledExecutor(); - final ExecutorService executor = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(2); final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( timer, @@ -111,30 +118,24 @@ public class PeriodicRunnableTests latch::countDown); scheduledRunnable.schedule(); - latch.await(520, TimeUnit.MILLISECONDS); + timer.getClock().elapse(Duration.ofMillis(520)); + timer.run(); // Check runnable executed once - Assert.assertEquals(1, latch.getCount()); + assertEquals(1, latch.getCount()); scheduledRunnable.cancel(); - latch.await(1000, TimeUnit.MILLISECONDS); + timer.getClock().elapse(Duration.ofSeconds(1)); + timer.run(); // Check runnable was not executed after cancel. - Assert.assertEquals(1, latch.getCount()); - - scheduledRunnable.cancel(); - executor.shutdownNow(); - timer.shutdownNow(); + assertEquals(1, latch.getCount()); } @Test public void scheduleExecuteRunnableIfPreviouslyCancelled() - throws InterruptedException { - final ScheduledExecutorService timer - = Executors.newSingleThreadScheduledExecutor(); - final ExecutorService executor = Executors.newSingleThreadExecutor(); - final CountDownLatch latch = new CountDownLatch(5); + final CountDownLatch latch = new CountDownLatch(10); final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( timer, executor, @@ -142,24 +143,26 @@ public class PeriodicRunnableTests latch::countDown); scheduledRunnable.schedule(); - latch.await(220, TimeUnit.MILLISECONDS); + timer.getClock().elapse(Duration.ofMillis(220)); + timer.run(); // Check runnable executed once - Assert.assertEquals(4, latch.getCount()); + assertEquals(9, latch.getCount()); scheduledRunnable.cancel(); - latch.await(1000, TimeUnit.MILLISECONDS); + timer.getClock().elapse(Duration.ofSeconds(1)); + timer.run(); // Check runnable was not executed after cancel. - Assert.assertEquals(4, latch.getCount()); + assertEquals(9, latch.getCount()); // Schedule again scheduledRunnable.schedule(); - latch.await(1000, TimeUnit.MILLISECONDS); - Assert.assertEquals(0, latch.getCount()); - - scheduledRunnable.cancel(); - executor.shutdownNow(); - timer.shutdownNow(); + for (int i = 0; i < 5; i++) + { + timer.getClock().elapse(Duration.ofMillis(200)); + timer.run(); + } + assertEquals(4, latch.getCount()); } } diff --git a/src/test/kotlin/org/ice4j/ConfigTest.kt b/src/test/kotlin/org/ice4j/ConfigTest.kt index bc0e361..542aa56 100644 --- a/src/test/kotlin/org/ice4j/ConfigTest.kt +++ b/src/test/kotlin/org/ice4j/ConfigTest.kt @@ -38,5 +38,5 @@ abstract class ConfigTest : ShouldSpec() { useNewConfig("new-${this::class.simpleName}", config, true, block) } - fun withLegacyConfig(config: Map, block: () -> Unit) = withSystemProperties(config) { block } + fun withLegacyConfig(config: Map, block: () -> Unit) = withSystemProperties(config) { block } } diff --git a/src/test/kotlin/org/ice4j/ice/AgentConfigTest.kt b/src/test/kotlin/org/ice4j/ice/AgentConfigTest.kt index 6a10e5b..5b52e9d 100644 --- a/src/test/kotlin/org/ice4j/ice/AgentConfigTest.kt +++ b/src/test/kotlin/org/ice4j/ice/AgentConfigTest.kt @@ -73,7 +73,8 @@ private val legacyConfig = mapOf( "org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL" to "5000", "org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS" to "5000", "org.ice4j.TERMINATION_DELAY" to "5000", - "org.ice4j.MAX_CHECK_LIST_SIZE" to "5000") + "org.ice4j.MAX_CHECK_LIST_SIZE" to "5000" +) private val newConfig = """ ice4j.consent-freshness.interval = 6 seconds diff --git a/test/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java b/test/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java deleted file mode 100644 index 778ca26..0000000 --- a/test/org/ice4j/socket/jdk8/MuxServerSocketChannelTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.ice4j.socket.jdk8; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -import org.ice4j.socket.DatagramPacketFilter; - -import junit.framework.TestCase; - -/** - * @author robertoandrade - */ -public class MuxServerSocketChannelTest extends TestCase { - - public void testOpenAndBindReuseWhenBindingToAllInterfacesFirst() throws IOException - { - SocketAddress allInterfaces = new InetSocketAddress("::", 4443); - SocketAddress oneInterface = new InetSocketAddress("localhost", 4443); - - MuxServerSocketChannel channelForAllInterfaces = - MuxServerSocketChannel.openAndBind(null, allInterfaces, 0, new DatagramPacketFilter() - { - @Override - public boolean accept(DatagramPacket p) - { - return false; - } - }); - - MuxServerSocketChannel channelForOneInterface = - MuxServerSocketChannel.openAndBind(null, oneInterface, 0, new DatagramPacketFilter() - { - @Override - public boolean accept(DatagramPacket p) - { - return false; - } - }); - - assertEquals(channelForAllInterfaces.getFDVal(), channelForOneInterface.getFDVal()); - } -}