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
This commit is contained in:
Ingo Bauersachs 2021-01-04 21:34:02 +01:00 committed by GitHub
parent a86c4be742
commit 34c2ce50ec
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 1615 additions and 1831 deletions

9
.editorconfig Normal file
View File

@ -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

90
.github/workflows/maven.yml vendored Normal file
View File

@ -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

6
bnd.bnd Normal file
View File

@ -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

261
pom.xml
View File

@ -4,22 +4,45 @@
<groupId>org.jitsi</groupId> <groupId>org.jitsi</groupId>
<artifactId>ice4j</artifactId> <artifactId>ice4j</artifactId>
<version>3.0-SNAPSHOT</version> <version>3.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>ice4j</name> <name>ice4j</name>
<description>A Java implementation of the ICE protocol</description>
<url>https://github.com/jitsi/ice4j</url> <url>https://github.com/jitsi/ice4j</url>
<organization>
<name>jitsi.org</name>
<url>https://jitsi.org</url>
</organization>
<developers>
<developer>
<id>org.jitsi</id>
<name>Jitsi Team</name>
<email>dev@jitsi.org</email>
</developer>
</developers>
<scm> <scm>
<url>https://github.com/jitsi/ice4j</url> <url>https://github.com/jitsi/ice4j</url>
<connection>scm:git:https://github.com/jitsi/ice4j.git</connection> <connection>scm:git:https://github.com/jitsi/ice4j.git</connection>
<developerConnection>scm:git:https://github.com/jitsi/ice4j.git</developerConnection> <developerConnection>scm:git:https://github.com/jitsi/ice4j.git</developerConnection>
<tag>HEAD</tag>
</scm> </scm>
<licenses>
<license>
<name>Apache-2.0</name>
<url>https://github.com/jitsi/ice4j/blob/master/LICENSE</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jicoco.version>1.1-53-gdc63c67</jicoco.version> <jicoco.version>1.1-73-gf8e9405</jicoco.version>
<kotlin.version>1.3.72</kotlin.version> <kotlin.version>1.3.72</kotlin.version>
<kotest.version>4.1.3</kotest.version> <kotest.version>4.1.3</kotest.version>
<junit.version>5.7.0</junit.version>
<dokka.version>1.4.20</dokka.version>
</properties> </properties>
<dependencies> <dependencies>
@ -36,7 +59,7 @@
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
<artifactId>jitsi-utils</artifactId> <artifactId>jitsi-utils</artifactId>
<version>1.0-59-g5dc2b5f</version> <version>1.0-72-gcf6d1f8</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>${project.groupId}</groupId> <groupId>${project.groupId}</groupId>
@ -46,16 +69,22 @@
<!-- test --> <!-- test -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>org.junit.platform</groupId>
<artifactId>junit</artifactId> <artifactId>junit-platform-launcher</artifactId>
<version>4.13.1</version> <version>1.7.0</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.kotest</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>kotest-runner-junit5-jvm</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>${kotest.version}</version> <version>${junit.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.kotest</groupId> <groupId>io.kotest</groupId>
@ -65,7 +94,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.kotest</groupId> <groupId>io.kotest</groupId>
<artifactId>kotest-runner-console-jvm</artifactId> <artifactId>kotest-runner-junit5-jvm</artifactId>
<version>${kotest.version}</version> <version>${kotest.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
@ -75,6 +104,12 @@
<version>${jicoco.version}</version> <version>${jicoco.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.6.28</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -157,61 +192,71 @@
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.felix</groupId> <groupId>com.github.gantsign.maven</groupId>
<artifactId>maven-bundle-plugin</artifactId> <artifactId>ktlint-maven-plugin</artifactId>
<version>3.0.1</version> <version>1.7.0</version>
<extensions>true</extensions> <configuration>
<sourceRoots>
<sourceRoot>${project.basedir}/src/main/kotlin</sourceRoot>
</sourceRoots>
<testSourceRoots>
<testSourceRoot>${project.basedir}/src/test/kotlin</testSourceRoot>
</testSourceRoots>
</configuration>
<executions>
<execution>
<id>check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
<version>5.2.0</version>
<executions>
<execution>
<goals>
<goal>bnd-process</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.10.4</version> <version>3.2.0</version>
<configuration> <configuration>
<show>private</show> <archive>
<nohelp>true</nohelp> <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version> <version>2.22.2</version>
<configuration> <configuration>
<includes> <includes>**/*</includes>
<include>**/*TestSuite.*</include>
</includes>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>com.github.siom79.japicmp</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>japicmp-maven-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>0.14.0</version> <version>2.8.2</version>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.8</version>
<extensions>true</extensions>
<configuration> <configuration>
<newVersion> <serverId>ossrh</serverId>
<file> <nexusUrl>https://oss.sonatype.org/</nexusUrl>
<path>${project.build.directory}/${project.build.finalName}.jar</path> <autoReleaseAfterClose>true</autoReleaseAfterClose>
</file>
</newVersion>
<oldVersion>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>1.0.0</version>
</dependency>
</oldVersion>
<parameter>
<onlyModified>true</onlyModified>
<breakBuildBasedOnSemanticVersioning>true</breakBuildBasedOnSemanticVersioning>
<reportOnlyFilename>true</reportOnlyFilename>
</parameter>
</configuration> </configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>cmp</goal>
</goals>
</execution>
</executions>
</plugin> </plugin>
</plugins> </plugins>
@ -346,24 +391,104 @@
</plugins> </plugins>
</build> </build>
</profile> </profile>
<profile>
<id>release</id>
<activation>
<property>
<name>release</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/kotlin</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.dokka</groupId>
<artifactId>dokka-maven-plugin</artifactId>
<version>${dokka.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>javadocJar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
<configuration>
<gpgArguments>
<arg>--pinentry-mode</arg>
<arg>loopback</arg>
</gpgArguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles> </profiles>
<repositories> <pluginRepositories>
<!-- Required for Dokka -->
<pluginRepository>
<id>jcenter</id>
<name>JCenter</name>
<url>https://jcenter.bintray.com/</url>
</pluginRepository>
</pluginRepositories>
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository> <repository>
<id>jitsi-maven-repository-releases</id> <id>ossrh</id>
<layout>default</layout> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
<name>Jitsi Maven Repository (Releases)</name>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<url>https://github.com/jitsi/jitsi-maven-repository/raw/master/releases/</url>
</repository> </repository>
<repository> </distributionManagement>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
</project> </project>

View File

@ -43,8 +43,8 @@ public class AttributeDecoder
* @throws StunException if bytes is not a valid STUN attribute. * @throws StunException if bytes is not a valid STUN attribute.
*/ */
public static Attribute decode(byte[] bytes, public static Attribute decode(byte[] bytes,
char offset, int offset,
char length) int length)
throws StunException throws StunException
{ {
if(bytes == null || bytes.length < Attribute.HEADER_LENGTH) if(bytes == null || bytes.length < Attribute.HEADER_LENGTH)

View File

@ -125,10 +125,7 @@ public abstract class AbstractUdpListener
try try
{ {
Message stunMessage Message stunMessage = Message.decode(buf, off, len);
= Message.decode(buf,
(char) off,
(char) len);
if (stunMessage.getMessageType() if (stunMessage.getMessageType()
!= Message.BINDING_REQUEST) != Message.BINDING_REQUEST)

View File

@ -1057,11 +1057,11 @@ public abstract class Message
* @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the * @throws StunException <tt>ILLEGAL_ARGUMENT</tt> if one or more of the
* arguments have invalid values. * 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 throws StunException
{ {
int originalOffset = offset; int originalOffset = offset;
arrayLen = (char)Math.min(binMessage.length, arrayLen); arrayLen = Math.min(binMessage.length, arrayLen);
if(arrayLen - offset < Message.HEADER_LENGTH) if(arrayLen - offset < Message.HEADER_LENGTH)
{ {
@ -1088,7 +1088,7 @@ public abstract class Message
| (binMessage[offset++] & 0xFF)); | (binMessage[offset++] & 0xFF));
/* copy the cookie */ /* copy the cookie */
byte cookie[] = new byte[4]; byte[] cookie = new byte[4];
System.arraycopy(binMessage, offset, cookie, 0, 4); System.arraycopy(binMessage, offset, cookie, 0, 4);
offset += 4; offset += 4;
@ -1106,20 +1106,20 @@ public abstract class Message
StunException.ILLEGAL_ARGUMENT, StunException.ILLEGAL_ARGUMENT,
"The given binary array does not seem to contain" "The given binary array does not seem to contain"
+ " a whole StunMessage: given " + " a whole StunMessage: given "
+ ((int) arrayLen) + arrayLen
+ " bytes of " + " bytes of "
+ message.getName() + message.getName()
+ " but expecting " + " but expecting "
+ (offset + TRANSACTION_ID_LENGTH + length)); + (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); System.arraycopy(binMessage, offset, tranID, 0, TRANSACTION_ID_LENGTH);
try try
{ {
if(rfc3489Compat) 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(cookie, 0, rfc3489TranID, 0, 4);
System.arraycopy(tranID, 0, rfc3489TranID, 4, System.arraycopy(tranID, 0, rfc3489TranID, 4,
TRANSACTION_ID_LENGTH); TRANSACTION_ID_LENGTH);

View File

@ -177,8 +177,8 @@ class MessageProcessingTask
{ {
stunMessage stunMessage
= Message.decode(message.getBytes(), = Message.decode(message.getBytes(),
(char) 0, 0,
(char) message.getMessageLength()); message.getMessageLength());
} }
catch (StunException ex) catch (StunException ex)
{ {

View File

@ -18,7 +18,6 @@ package org.ice4j.ice
import org.jitsi.metaconfig.config import org.jitsi.metaconfig.config
import java.time.Duration import java.time.Duration
import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource
class AgentConfig { class AgentConfig {
@ -60,4 +59,4 @@ class AgentConfig {
@JvmField @JvmField
val config = AgentConfig() val config = AgentConfig()
} }
} }

View File

@ -19,7 +19,6 @@ package org.ice4j.ice.harvest
import org.jitsi.metaconfig.config import org.jitsi.metaconfig.config
import org.jitsi.metaconfig.optionalconfig import org.jitsi.metaconfig.optionalconfig
import java.time.Duration import java.time.Duration
import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource import org.jitsi.config.JitsiConfig.Companion.newConfig as configSource
class HarvestConfig { class HarvestConfig {
@ -64,8 +63,8 @@ class HarvestConfig {
fun stunMappingCandidateHarvesterAddresses() = stunMappingCandidateHarvesterAddresses fun stunMappingCandidateHarvesterAddresses() = stunMappingCandidateHarvesterAddresses
val enableAwsHarvester: Boolean by config { val enableAwsHarvester: Boolean by config {
"org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER".from(configSource).transformedBy { !it } "org.ice4j.ice.harvest.DISABLE_AWS_HARVESTER".from(configSource).transformedBy { !it }
"ice4j.harvest.mapping.aws.enabled".from(configSource) "ice4j.harvest.mapping.aws.enabled".from(configSource)
} }
fun enableAwsHarvester() = enableAwsHarvester fun enableAwsHarvester() = enableAwsHarvester
@ -79,4 +78,4 @@ class HarvestConfig {
@JvmField @JvmField
val config = HarvestConfig() val config = HarvestConfig()
} }
} }

View File

@ -19,18 +19,18 @@ package org.ice4j;
import java.util.*; import java.util.*;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* Test event dispatching for both client and server. * Test event dispatching for both client and server.
*` *`
* @author Emil Ivov * @author Emil Ivov
*/ */
public class MessageEventDispatchingTest extends TestCase public class MessageEventDispatchingTest
{ {
/** /**
* The stack that we are using for the tests. * The stack that we are using for the tests.
@ -95,10 +95,9 @@ public class MessageEventDispatchingTest extends TestCase
* *
* @throws Exception if anything goes wrong. * @throws Exception if anything goes wrong.
*/ */
protected void setUp() throws Exception @BeforeEach
public void setUp() throws Exception
{ {
super.setUp();
stunStack = new StunStack(); stunStack = new StunStack();
clientSock = new IceUdpSocketWrapper( clientSock = new IceUdpSocketWrapper(
@ -126,7 +125,8 @@ public class MessageEventDispatchingTest extends TestCase
* *
* @throws Exception if anything goes wrong. * @throws Exception if anything goes wrong.
*/ */
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
stunStack.removeSocket(clientAddress); stunStack.removeSocket(clientAddress);
stunStack.removeSocket(serverAddress); stunStack.removeSocket(serverAddress);
@ -138,8 +138,6 @@ public class MessageEventDispatchingTest extends TestCase
requestCollector = null; requestCollector = null;
responseCollector = null; responseCollector = null;
super.tearDown();
} }
/** /**
@ -147,6 +145,7 @@ public class MessageEventDispatchingTest extends TestCase
* *
* @throws Exception upon a stun failure * @throws Exception upon a stun failure
*/ */
@Test
public void testClientTransactionTimeouts() throws Exception public void testClientTransactionTimeouts() throws Exception
{ {
String oldRetransValue = System.getProperty( String oldRetransValue = System.getProperty(
@ -156,13 +155,11 @@ public class MessageEventDispatchingTest extends TestCase
responseCollector); responseCollector);
responseCollector.waitForTimeout(); responseCollector.waitForTimeout();
assertEquals( assertEquals(1, responseCollector.receivedResponses.size(),
"No timeout was produced upon expiration of a client transaction", "No timeout was produced upon expiration of a client transaction");
responseCollector.receivedResponses.size(), 1);
assertEquals( assertEquals("timeout", responseCollector.receivedResponses.get(0),
"No timeout was produced upon expiration of a client transaction", "No timeout was produced upon expiration of a client transaction");
responseCollector.receivedResponses.get(0), "timeout");
//restore the retransmissions prop in case others are counting on //restore the retransmissions prop in case others are counting on
//defaults. //defaults.
@ -178,6 +175,7 @@ public class MessageEventDispatchingTest extends TestCase
* *
* @throws java.lang.Exception upon any failure * @throws java.lang.Exception upon any failure
*/ */
@Test
public void testEventDispatchingUponIncomingRequests() throws Exception public void testEventDispatchingUponIncomingRequests() throws Exception
{ {
//prepare to listen //prepare to listen
@ -189,8 +187,8 @@ public class MessageEventDispatchingTest extends TestCase
requestCollector.waitForRequest(); requestCollector.waitForRequest();
//verify //verify
assertTrue("No MessageEvents have been dispatched", assertEquals(1, requestCollector.receivedRequests.size(),
requestCollector.receivedRequests.size() == 1); "No MessageEvents have been dispatched");
} }
/** /**
@ -199,6 +197,7 @@ public class MessageEventDispatchingTest extends TestCase
* *
* @throws java.lang.Exception upon any failure * @throws java.lang.Exception upon any failure
*/ */
@Test
public void testSelectiveEventDispatchingUponIncomingRequests() public void testSelectiveEventDispatchingUponIncomingRequests()
throws Exception throws Exception
{ {
@ -216,19 +215,17 @@ public class MessageEventDispatchingTest extends TestCase
requestCollector2.waitForRequest(); requestCollector2.waitForRequest();
//verify //verify
assertTrue( assertEquals(0, requestCollector.receivedRequests.size(),
"A MessageEvent was received by a non-interested selective listener", "A MessageEvent was received by a non-interested selective listener");
requestCollector.receivedRequests.size() == 0); assertEquals(1, requestCollector2.receivedRequests.size(),
assertTrue( "No MessageEvents have been dispatched for a selective listener");
"No MessageEvents have been dispatched for a selective listener",
requestCollector2.receivedRequests.size() == 1);
} }
/** /**
* Makes sure that we receive response events. * Makes sure that we receive response events.
* @throws Exception if we screw up. * @throws Exception if we screw up.
*/ */
@Test
public void testServerResponseRetransmissions() throws Exception public void testServerResponseRetransmissions() throws Exception
{ {
//prepare to listen //prepare to listen
@ -249,15 +246,14 @@ public class MessageEventDispatchingTest extends TestCase
responseCollector.waitForResponse(); responseCollector.waitForResponse();
//verify that we got the response. //verify that we got the response.
assertTrue( assertEquals(1, responseCollector.receivedResponses.size(),
"There were no retransmissions of a binding response", "There were no retransmissions of a binding response");
responseCollector.receivedResponses.size() == 1 );
} }
/** /**
* A utility class we use to collect incoming requests. * 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. */ /** all requests we've received so far. */
public final Vector<StunMessageEvent> receivedRequests = new Vector<>(); public final Vector<StunMessageEvent> receivedRequests = new Vector<>();

View File

@ -243,20 +243,4 @@ public class MsgFixture
0x00, 0x20, 0x00, 0x21, 0x00, 0x20, 0x00, 0x21,
0x00, 0x22, 0x00, 0x22 0x00, 0x22, 0x00, 0x22
}; };
public MsgFixture()
{
}
public void setUp()
{
}
public void tearDown()
{
}
} }

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -17,14 +17,15 @@
*/ */
package org.ice4j; package org.ice4j;
import java.net.*;
import java.util.*; import java.util.*;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*; import org.ice4j.socket.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* Test how client and server behave, how they recognize/adopt messages and * Test how client and server behave, how they recognize/adopt messages and
* how they both handle retransmissions (i.e. client transactions should make * how they both handle retransmissions (i.e. client transactions should make
@ -32,19 +33,17 @@ import org.ice4j.stack.*;
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class TransactionSupportTests extends TestCase public class TransactionSupportTests
{ {
/** /**
* The client address we use for this test. * The client address we use for this test.
*/ */
TransportAddress clientAddress TransportAddress clientAddress;
= new TransportAddress("127.0.0.1", 5216, Transport.UDP);
/** /**
* The client address we use for this test. * The client address we use for this test.
*/ */
TransportAddress serverAddress TransportAddress serverAddress;
= new TransportAddress("127.0.0.1", 5255, Transport.UDP);
/** /**
* The socket the client uses in this test. * The socket the client uses in this test.
@ -86,15 +85,19 @@ public class TransactionSupportTests extends TestCase
* *
* @throws Exception if something goes bad. * @throws Exception if something goes bad.
*/ */
protected void setUp() @BeforeEach
public void setUp()
throws Exception throws Exception
{ {
super.setUp();
clientSock = new IceUdpSocketWrapper( clientSock = new IceUdpSocketWrapper(
new SafeCloseDatagramSocket(clientAddress)); new SafeCloseDatagramSocket(new InetSocketAddress("127.0.0.1", 0)));
serverSock = new IceUdpSocketWrapper( 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 = new StunStack();
stunStack.addSocket(clientSock); stunStack.addSocket(clientSock);
@ -129,7 +132,8 @@ public class TransactionSupportTests extends TestCase
* *
* @throws Exception if something does not go as planned. * @throws Exception if something does not go as planned.
*/ */
protected void tearDown() @AfterEach
public void tearDown()
throws Exception throws Exception
{ {
stunStack.removeSocket(clientAddress); stunStack.removeSocket(clientAddress);
@ -156,8 +160,6 @@ public class TransactionSupportTests extends TestCase
System.setProperty( System.setProperty(
StackProperties.FIRST_CTRAN_RETRANS_AFTER, StackProperties.FIRST_CTRAN_RETRANS_AFTER,
""); "");
super.tearDown();
} }
/** /**
@ -165,6 +167,7 @@ public class TransactionSupportTests extends TestCase
* *
* @throws java.lang.Exception upon any failure * @throws java.lang.Exception upon any failure
*/ */
@Test
public void testClientRetransmissions() throws Exception public void testClientRetransmissions() throws Exception
{ {
String oldRetransValue = System.getProperty( String oldRetransValue = System.getProperty(
@ -195,11 +198,10 @@ public class TransactionSupportTests extends TestCase
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue("No retransmissions of the request have been received", assertTrue(reqs.size() > 1,
reqs.size() > 1); "No retransmissions of the request have been received");
assertTrue("The binding request has been retransmitted more than it " assertTrue(reqs.size() >= 3,
+"should have!", "The binding request has been retransmitted more than it should have!");
reqs.size() >= 3);
//restore the retransmissions prop in case others are counting on //restore the retransmissions prop in case others are counting on
//defaults. //defaults.
@ -222,6 +224,7 @@ public class TransactionSupportTests extends TestCase
* *
* @throws Exception if anything goes wrong. * @throws Exception if anything goes wrong.
*/ */
@Test
public void testServerRetransmissionHiding() throws Exception public void testServerRetransmissionHiding() throws Exception
{ {
String oldRetransValue = System.getProperty( String oldRetransValue = System.getProperty(
@ -244,9 +247,8 @@ public class TransactionSupportTests extends TestCase
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue( assertTrue(reqs.size() <= 1,
"Retransmissions of a binding request were propagated " "Retransmissions of a binding request were propagated to the server");
+ "to the server", reqs.size() <= 1 );
//restore the retransmissions prop in case others are counting on //restore the retransmissions prop in case others are counting on
//defaults. //defaults.
@ -264,6 +266,7 @@ public class TransactionSupportTests extends TestCase
* *
* @throws Exception if we screw up. * @throws Exception if we screw up.
*/ */
@Test
public void testServerResponseRetransmissions() throws Exception public void testServerResponseRetransmissions() throws Exception
{ {
String oldRetransValue = System.getProperty( String oldRetransValue = System.getProperty(
@ -303,10 +306,9 @@ public class TransactionSupportTests extends TestCase
Thread.sleep(500); Thread.sleep(500);
//verify that we received a fair number of retransmitted responses. //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: " "There were too few retransmissions of a binding response: "
+responseCollector.receivedResponses.size(), +responseCollector.receivedResponses.size());
responseCollector.receivedResponses.size() < 3 );
//restore the retransmissions prop in case others are counting on //restore the retransmissions prop in case others are counting on
//defaults. //defaults.
@ -323,6 +325,7 @@ public class TransactionSupportTests extends TestCase
* A (very) weak test, verifying that transaction IDs are unique. * A (very) weak test, verifying that transaction IDs are unique.
* @throws Exception in case we feel like it. * @throws Exception in case we feel like it.
*/ */
@Test
public void testUniqueIDs() throws Exception public void testUniqueIDs() throws Exception
{ {
stunStack.addRequestListener(serverAddress, requestCollector); stunStack.addRequestListener(serverAddress, requestCollector);
@ -366,10 +369,11 @@ public class TransactionSupportTests extends TestCase
StunMessageEvent evt2 = reqs2.get(0); StunMessageEvent evt2 = reqs2.get(0);
assertFalse( assertFalse(Arrays.equals(
"Consecutive requests were assigned the same transaction id", evt1.getMessage().getTransactionID(),
Arrays.equals( evt1.getMessage().getTransactionID(), evt2.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. * @throws Exception if the gods so decide.
*/ */
@Test
public void testClientTransactionMaxRetransmisssionsConfigurationParameter() public void testClientTransactionMaxRetransmisssionsConfigurationParameter()
throws Exception throws Exception
{ {
@ -404,13 +409,10 @@ public class TransactionSupportTests extends TestCase
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue("No retransmissions of the request have been received", assertTrue(reqs.size() > 1,
reqs.size() > 1); "No retransmissions of the request have been received");
assertEquals( assertEquals(3, reqs.size(),
"The MAX_RETRANSMISSIONS param was not taken into account!", "The MAX_RETRANSMISSIONS param was not taken into account!");
reqs.size(),
3);
} }
/** /**
@ -419,6 +421,7 @@ public class TransactionSupportTests extends TestCase
* *
* @throws Exception if we are having a bad day. * @throws Exception if we are having a bad day.
*/ */
@Test
public void testMinWaitIntervalConfigurationParameter() public void testMinWaitIntervalConfigurationParameter()
throws Exception throws Exception
{ {
@ -442,8 +445,8 @@ public class TransactionSupportTests extends TestCase
//verify //verify
Vector<?> reqs = requestCollector.getRequestsForTransaction( Vector<?> reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertTrue("A retransmissions of the request was sent too early", assertTrue(reqs.size() < 2,
reqs.size() < 2); "A retransmissions of the request was sent too early");
//wait for a send //wait for a send
Thread.sleep(110); Thread.sleep(110);
@ -452,8 +455,8 @@ public class TransactionSupportTests extends TestCase
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
//verify //verify
assertEquals("A retransmissions of the request was not sent", assertEquals(2, reqs.size(),
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. * @throws Exception if the gods so decide.
*/ */
@Test
public void testMaxWaitIntervalConfigurationParameter() public void testMaxWaitIntervalConfigurationParameter()
throws Exception throws Exception
{ {
@ -488,10 +492,8 @@ public class TransactionSupportTests extends TestCase
Vector<StunMessageEvent> reqs Vector<StunMessageEvent> reqs
= requestCollector.getRequestsForTransaction( = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertEquals("Not all retransmissions were made for the expected period " assertEquals(12, reqs.size(),
+"of time", "Not all retransmissions were made for the expected period of time");
12,
reqs.size());
//wait for a send //wait for a send
Thread.sleep(1800); Thread.sleep(1800);
@ -499,22 +501,20 @@ public class TransactionSupportTests extends TestCase
//verify //verify
reqs = requestCollector.getRequestsForTransaction( reqs = requestCollector.getRequestsForTransaction(
bindingRequest.getTransactionID()); bindingRequest.getTransactionID());
assertEquals("A retransmissions of the request was sent, while not " assertEquals(12, reqs.size(),
+"supposed to", "A retransmissions of the request was sent, while not supposed to");
12,
reqs.size());
} }
/** /**
* A simply utility for asynchronous collection of requests. * A simply utility for asynchronous collection of requests.
*/ */
private class PlainRequestCollector private static class PlainRequestCollector
implements RequestListener implements RequestListener
{ {
/** /**
* *
*/ */
private Vector<StunMessageEvent> receivedRequestsVector private final Vector<StunMessageEvent> receivedRequestsVector
= new Vector<>(); = new Vector<>();
/** /**

View File

@ -17,46 +17,40 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import java.util.*; import static org.junit.jupiter.api.Assertions.*;
import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class AddressAttributeTest extends TestCase { public class AddressAttributeTest
{
private AddressAttribute addressAttribute = null; private AddressAttribute addressAttribute = null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
public AddressAttributeTest(String name) { @BeforeEach
super(name); public void setUp() throws Exception
} {
protected void setUp() throws Exception {
super.setUp();
addressAttribute = new MappedAddressAttribute(); addressAttribute = new MappedAddressAttribute();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
msgFixture.setUp();
} }
protected void tearDown() throws Exception { @AfterEach
public void tearDown() throws Exception
{
addressAttribute = null; addressAttribute = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Verify that AddressAttribute descendants have correctly set types and * Verify that AddressAttribute descendants have correctly set types and
* names. * names.
*/ */
public void testAddressAttributeDescendants() { @Test
public void testAddressAttributeDescendants()
{
char expectedType; char expectedType;
char actualType; char actualType;
String expectedName; String expectedName;
@ -71,10 +65,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "MAPPED-ADDRESS"; expectedName = "MAPPED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("MappedAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "MappedAddressAttribute does not the right type.");
assertEquals("MappedAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "MappedAddressAttribute does not the right name.");
//SOURCE-ADDRESS //SOURCE-ADDRESS
@ -86,10 +80,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "SOURCE-ADDRESS"; expectedName = "SOURCE-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("SourceAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "SourceAddressAttribute does not the right type.");
assertEquals("SourceAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "SourceAddressAttribute does not the right name.");
//CHANGED-ADDRESS //CHANGED-ADDRESS
@ -101,10 +95,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "CHANGED-ADDRESS"; expectedName = "CHANGED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("ChangedAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "ChangedAddressAttribute does not the right type.");
assertEquals("ChangedAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "ChangedAddressAttribute does not the right name.");
//RESPONSE-ADDRESS //RESPONSE-ADDRESS
@ -116,10 +110,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "RESPONSE-ADDRESS"; expectedName = "RESPONSE-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("ResponseAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "ResponseAddressAttribute does not the right type.");
assertEquals("ResponseAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "ResponseAddressAttribute does not the right name.");
//REFLECTED-FROM //REFLECTED-FROM
@ -131,10 +125,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "REFLECTED-FROM"; expectedName = "REFLECTED-FROM";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("ReflectedFromAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "ReflectedFromAttribute does not the right type.");
assertEquals("ReflectedFromAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "ReflectedFromAttribute does not the right name.");
//REFLECTED-FROM //REFLECTED-FROM
addressAttribute = new ReflectedFromAttribute(); addressAttribute = new ReflectedFromAttribute();
@ -145,10 +139,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "REFLECTED-FROM"; expectedName = "REFLECTED-FROM";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("ReflectedFromAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "ReflectedFromAttribute does not the right type.");
assertEquals("ReflectedFromAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "ReflectedFromAttribute does not the right name.");
//XOR-MAPPED-ADDRESS //XOR-MAPPED-ADDRESS
addressAttribute = new XorMappedAddressAttribute(); addressAttribute = new XorMappedAddressAttribute();
@ -159,10 +153,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "XOR-MAPPED-ADDRESS"; expectedName = "XOR-MAPPED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("XorMappedAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "XorMappedAddressAttribute does not the right type.");
assertEquals("XorMappedAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "XorMappedAddressAttribute does not the right name.");
/* ALTERNATE-SERVER */ /* ALTERNATE-SERVER */
addressAttribute = new AlternateServerAttribute(); addressAttribute = new AlternateServerAttribute();
@ -173,10 +167,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "ALTERNATE-SERVER"; expectedName = "ALTERNATE-SERVER";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("AlternateServerAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "AlternateServerAttribute does not the right type.");
assertEquals("AlternateAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "AlternateAttribute does not the right name.");
/* XOR-PEER-ADDRESS */ /* XOR-PEER-ADDRESS */
@ -188,10 +182,10 @@ public class AddressAttributeTest extends TestCase {
expectedName = "XOR-PEER-ADDRESS"; expectedName = "XOR-PEER-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("XorPeerAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "XorPeerAddressAttribute does not the right type.");
assertEquals("XorPeerAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "XorPeerAddressAttribute does not the right name.");
/* XOR-RELAYED-ADDRESS */ /* XOR-RELAYED-ADDRESS */
addressAttribute = new XorRelayedAddressAttribute(); addressAttribute = new XorRelayedAddressAttribute();
@ -202,15 +196,16 @@ public class AddressAttributeTest extends TestCase {
expectedName = "XOR-RELAYED-ADDRESS"; expectedName = "XOR-RELAYED-ADDRESS";
actualName = addressAttribute.getName(); actualName = addressAttribute.getName();
assertEquals("XorRelayedAddressAttribute does not the right type.", assertEquals(expectedType, actualType,
expectedType, actualType); "XorRelayedAddressAttribute does not the right type.");
assertEquals("XorRelayedAddressAttribute does not the right name.", assertEquals(expectedName, actualName,
expectedName, actualName); "XorRelayedAddressAttribute does not the right name.");
} }
/** /**
* Verifies that xorred address-es are properly xor-ed for IPv4 addresses. * Verifies that xorred address-es are properly xor-ed for IPv4 addresses.
*/ */
@Test
public void testXorMappedAddressXoring_v4() public void testXorMappedAddressXoring_v4()
{ {
XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute(); XorMappedAddressAttribute addressAttribute = new XorMappedAddressAttribute();
@ -223,11 +218,12 @@ public class AddressAttributeTest extends TestCase {
TransportAddress xorredAddr = addressAttribute.applyXor( TransportAddress xorredAddr = addressAttribute.applyXor(
new byte[]{(byte)130,79,95,53,0,0,0,0,0,0,0,0,0,0,0,0,0}); 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...", assertArrayEquals(
Arrays.equals(xorredAddr.getAddressBytes(), new byte[]{0,0,0,0})); xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0 },
"Xorring the address with itself didn't return 00000...");
assertTrue("Port was not xorred", assertNotEquals(xorredAddr.getPort(), testAddress.getPort(),
testAddress.getPort() != xorredAddr.getPort()); "Port was not xorred");
//Test xor-ing the original with the xored - should get the xor code //Test xor-ing the original with the xored - should get the xor code
addressAttribute.setAddress(testAddress); addressAttribute.setAddress(testAddress);
@ -237,13 +233,11 @@ public class AddressAttributeTest extends TestCase {
xorredAddr = xorredAddr =
addressAttribute.applyXor(xorredAddr.getAddressBytes()); addressAttribute.applyXor(xorredAddr.getAddressBytes());
assertTrue("Xorring the original with the xor-ed didn't " assertArrayEquals(
+"return the code..", xorredAddr.getAddressBytes(), new byte[] { 21, 22, 23, 24 },
Arrays.equals( xorredAddr.getAddressBytes(), "Xorring the original with the xor-ed didn't return the code.");
new byte[]{21,22,23,24}));
assertTrue("Port was not xorred", assertNotEquals(0xFFFF, testAddress.getPort(), "Port was not xorred");
testAddress.getPort() != 0xFFFF);
//Test double xor-ing - should get the original //Test double xor-ing - should get the original
addressAttribute.setAddress(testAddress); addressAttribute.setAddress(testAddress);
@ -254,13 +248,14 @@ public class AddressAttributeTest extends TestCase {
xorredAddr = addressAttribute.applyXor( xorredAddr = addressAttribute.applyXor(
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}); 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 ...", assertEquals(testAddress, xorredAddr,
testAddress, xorredAddr); "Double xorring didn't give the original");
} }
/** /**
* Verifies that xorred address-es are properly xor-ed for IPv6 addresses. * Verifies that xorred address-es are properly xor-ed for IPv6 addresses.
*/ */
@Test
public void testXorMappedAddressXoring_v6() public void testXorMappedAddressXoring_v6()
{ {
XorMappedAddressAttribute addressAttribute XorMappedAddressAttribute addressAttribute
@ -278,15 +273,15 @@ public class AddressAttributeTest extends TestCase {
(byte)0x02, (byte)0x02, (byte)0x8a, (byte)0xff, (byte)0x02, (byte)0x02, (byte)0x8a, (byte)0xff,
(byte)0xfe, (byte)0xbe, (byte)0x13, (byte)0x0b}); (byte)0xfe, (byte)0xbe, (byte)0x13, (byte)0x0b});
assertTrue("Xorring the address with itself didn't return 00000...", assertArrayEquals(
Arrays.equals(xorredAddr.getAddressBytes(), xorredAddr.getAddressBytes(), new byte[] { 0, 0, 0, 0,
new byte[]{0,0,0,0, 0, 0, 0, 0,
0,0,0,0, 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", assertNotEquals(testAddress.getPort(), xorredAddr.getPort(),
testAddress.getPort() != xorredAddr.getPort()); "Port was not xorred");
//Test xor-ing the original with the xored - should get the xor code //Test xor-ing the original with the xored - should get the xor code
addressAttribute.setAddress(testAddress); addressAttribute.setAddress(testAddress);
@ -295,13 +290,13 @@ public class AddressAttributeTest extends TestCase {
xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes()); xorredAddr = addressAttribute.applyXor(xorredAddr.getAddressBytes());
assertTrue("Xorring the original with the xor-ed didn't return the code..", assertArrayEquals(
Arrays.equals( xorredAddr.getAddressBytes(),
xorredAddr.getAddressBytes(), new byte[] { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36})); 35, 36 },
"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 //Test double xor-ing - should get the original
addressAttribute.setAddress(testAddress); addressAttribute.setAddress(testAddress);
@ -312,8 +307,8 @@ public class AddressAttributeTest extends TestCase {
xorredAddr = addressAttribute.applyXor( xorredAddr = addressAttribute.applyXor(
new byte[]{21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}); 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 ...", assertEquals(testAddress, xorredAddr,
testAddress, xorredAddr); "Double xorring didn't give the original");
} }
/** /**
@ -321,6 +316,7 @@ public class AddressAttributeTest extends TestCase {
* *
* @throws StunException if something goes wrong * @throws StunException if something goes wrong
*/ */
@Test
public void testDecodeAttributeBody() throws StunException { public void testDecodeAttributeBody() throws StunException {
byte[] attributeValue = msgFixture.mappedAddress; byte[] attributeValue = msgFixture.mappedAddress;
char offset = Attribute.HEADER_LENGTH; char offset = Attribute.HEADER_LENGTH;
@ -330,12 +326,12 @@ public class AddressAttributeTest extends TestCase {
assertEquals( assertEquals(
"AddressAttribute.decode() did not properly decode the port field.", MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort(),
MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort()); "AddressAttribute.decode() did not properly decode the port field.");
assertTrue( assertArrayEquals(
"AddressAttribute.decode() did not properly decode the address field.", MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, addressAttribute.getAddressBytes(),
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. * Test whetner sample binary arrays are correctly decoded.
* @throws StunException if something goes wrong * @throws StunException if something goes wrong
*/ */
@Test
public void testDecodeAttributeBodyv6() throws StunException { public void testDecodeAttributeBodyv6() throws StunException {
byte[] attributeValue = msgFixture.mappedAddressv6; byte[] attributeValue = msgFixture.mappedAddressv6;
char offset = Attribute.HEADER_LENGTH; char offset = Attribute.HEADER_LENGTH;
@ -352,14 +349,13 @@ public class AddressAttributeTest extends TestCase {
addressAttribute.decodeAttributeBody(attributeValue, offset, length); addressAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("decode() failed for an IPv6 Addr's port.", assertEquals(MsgFixture.ADDRESS_ATTRIBUTE_PORT,
MsgFixture.ADDRESS_ATTRIBUTE_PORT, addressAttribute.getPort(),
addressAttribute.getPort()); "decode() failed for an IPv6 Addr's port.");
assertTrue("AddressAttribute.decode() failed for an IPv6 address.", assertArrayEquals(
Arrays.equals( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6, MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
addressAttribute.getAddressBytes())); 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 * @throws Exception java.lang.Exception if we fail
*/ */
@Test
public void testEncode() public void testEncode()
throws Exception throws Exception
{ {
@ -378,9 +375,8 @@ public class AddressAttributeTest extends TestCase {
Transport.UDP)); Transport.UDP));
byte[] actualReturn = addressAttribute.encode(); byte[] actualReturn = addressAttribute.encode();
assertTrue("AddressAttribute.encode() did not " assertArrayEquals(expectedReturn, actualReturn,
+"properly encode a sample attribute", "AddressAttribute.encode() did not properly encode a sample attribute");
Arrays.equals( expectedReturn, actualReturn));
} }
/** /**
@ -388,6 +384,7 @@ public class AddressAttributeTest extends TestCase {
* *
* @throws Exception java.lang.Exception if we fail * @throws Exception java.lang.Exception if we fail
*/ */
@Test
public void testEncodev6() public void testEncodev6()
throws Exception throws Exception
{ {
@ -398,8 +395,8 @@ public class AddressAttributeTest extends TestCase {
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
byte[] actualReturn = addressAttribute.encode(); byte[] actualReturn = addressAttribute.encode();
assertTrue("An AddressAttribute did not properly encode an IPv6 addr.", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( 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 * @throws Exception java.lang.Exception if we fail
*/ */
@Test
public void testEquals() public void testEquals()
throws Exception throws Exception
{ {
@ -417,8 +415,8 @@ public class AddressAttributeTest extends TestCase {
boolean expectedReturn = false; boolean expectedReturn = false;
boolean actualReturn = addressAttribute.equals(target); boolean actualReturn = addressAttribute.equals(target);
assertEquals("AddressAttribute.equals() failed against a null target.", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "AddressAttribute.equals() failed against a null target.");
//difference test //difference test
target = new MappedAddressAttribute(); target = new MappedAddressAttribute();
@ -434,9 +432,8 @@ public class AddressAttributeTest extends TestCase {
expectedReturn = false; expectedReturn = false;
actualReturn = addressAttribute.equals(target); actualReturn = addressAttribute.equals(target);
assertEquals( assertEquals(expectedReturn, actualReturn,
"AddressAttribute.equals() failed against a different target.", "AddressAttribute.equals() failed against a different target.");
expectedReturn, actualReturn);
//equality test //equality test
target.setAddress( new TransportAddress( target.setAddress( new TransportAddress(
@ -445,9 +442,8 @@ public class AddressAttributeTest extends TestCase {
expectedReturn = true; expectedReturn = true;
actualReturn = addressAttribute.equals(target); actualReturn = addressAttribute.equals(target);
assertEquals( assertEquals(expectedReturn, actualReturn,
"AddressAttribute.equals() failed against an equal target.", "AddressAttribute.equals() failed against an equal target.");
expectedReturn, actualReturn);
//ipv6 equality test //ipv6 equality test
target.setAddress( new TransportAddress( target.setAddress( new TransportAddress(
@ -461,8 +457,8 @@ public class AddressAttributeTest extends TestCase {
expectedReturn = true; expectedReturn = true;
actualReturn = addressAttribute.equals(target); actualReturn = addressAttribute.equals(target);
assertEquals("AddressAttribute.equals() failed for IPv6 addresses.", assertEquals(expectedReturn, actualReturn,
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 * @throws Exception java.lang.Exception if we fail
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
throws Exception throws Exception
{ {
@ -482,8 +479,8 @@ public class AddressAttributeTest extends TestCase {
char actualReturn = addressAttribute.getDataLength(); char actualReturn = addressAttribute.getDataLength();
assertEquals("Datalength is not propoerly calculated", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "Datalength is not propoerly calculated");
expectedReturn = 20;//1-padding + 1-family + 2-port + 16-address expectedReturn = 20;//1-padding + 1-family + 2-port + 16-address
addressAttribute.setAddress( new TransportAddress( addressAttribute.setAddress( new TransportAddress(
@ -492,8 +489,8 @@ public class AddressAttributeTest extends TestCase {
actualReturn = addressAttribute.getDataLength(); actualReturn = addressAttribute.getDataLength();
assertEquals("Datalength is not propoerly calculated", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "Datalength is not propoerly calculated");
} }
/** /**
@ -501,6 +498,7 @@ public class AddressAttributeTest extends TestCase {
* *
* @throws Exception java.lang.Exception if we fail * @throws Exception java.lang.Exception if we fail
*/ */
@Test
public void testGetFamily() public void testGetFamily()
throws Exception throws Exception
{ {
@ -509,8 +507,8 @@ public class AddressAttributeTest extends TestCase {
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
byte actualReturn = addressAttribute.getFamily(); byte actualReturn = addressAttribute.getFamily();
assertEquals("Address family was not 1 for an IPv4", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "Address family was not 1 for an IPv4");
//ipv6 //ipv6
expectedReturn = 2; expectedReturn = 2;
@ -518,9 +516,7 @@ public class AddressAttributeTest extends TestCase {
MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6, MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_V6,
MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP)); MsgFixture.ADDRESS_ATTRIBUTE_PORT, Transport.UDP));
actualReturn = addressAttribute.getFamily(); actualReturn = addressAttribute.getFamily();
assertEquals("Address family was not 2 for an IPv6 address", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "Address family was not 2 for an IPv6 address");
} }
} }

View File

@ -17,28 +17,23 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import org.ice4j.*; 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 * We have already tested individual decode methods, so our job here
* is to verify that that AttributeDecoder.decode distributes the right way. * is to verify that that AttributeDecoder.decode distributes the right way.
*/ */
public class AttributeDecoderTest extends TestCase public class AttributeDecoderTest {
{
private MsgFixture msgFixture; private MsgFixture msgFixture;
private byte[] expectedAttributeValue = null; 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(); msgFixture = new MsgFixture();
//init a sample body //init a sample body
@ -48,18 +43,15 @@ public class AttributeDecoderTest extends TestCase
System.arraycopy(msgFixture.unknownOptionalAttribute, offset, System.arraycopy(msgFixture.unknownOptionalAttribute, offset,
expectedAttributeValue, 0, expectedAttributeValue, 0,
expectedAttributeValue.length); expectedAttributeValue.length);
msgFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
@Test
public void testDecodeMappedAddress() public void testDecodeMappedAddress()
throws Exception throws Exception
{ {
@ -79,11 +71,11 @@ public class AttributeDecoderTest extends TestCase
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals( assertEquals(expectedReturn, actualReturn,
"AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute", "AttributeDecoder.decode() failed for a MAPPED-ADDRESS attribute");
expectedReturn, actualReturn);
} }
@Test
public void testDecodeMappedAddress_v6() public void testDecodeMappedAddress_v6()
throws Exception throws Exception
{ {
@ -104,10 +96,12 @@ public class AttributeDecoderTest extends TestCase
bytes, offset, length); bytes, offset, length);
assertEquals( 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() public void testDecodeChangeRequest()
throws Exception throws Exception
{ {
@ -123,12 +117,13 @@ public class AttributeDecoderTest extends TestCase
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals("AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "AttributeDecoder.decode() failed for a CHANGE-REQUEST attribute"
);
} }
public void testDecodeErrorCode() @Test
public void testDecodeErrorCode()
throws Exception throws Exception
{ {
// //
@ -144,13 +139,12 @@ public class AttributeDecoderTest extends TestCase
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals( assertEquals(expectedReturn, actualReturn,
"AttributeDecoder.decode() failed for a ERROR-CODE attribute", "AttributeDecoder.decode() failed for a ERROR-CODE attribute");
expectedReturn, actualReturn);
} }
public void testDecodeUnknownAttributes() @Test
public void testDecodeUnknownAttributes()
throws Exception throws Exception
{ {
//unknown attributes //unknown attributes
@ -168,13 +162,12 @@ public class AttributeDecoderTest extends TestCase
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals( assertEquals(expectedReturn, actualReturn,
"AttributeDecoder.decode() failed for a ERROR-CODE attribute", "AttributeDecoder.decode() failed for a ERROR-CODE attribute");
expectedReturn, actualReturn);
} }
public void testDecodeUnknownOptionalAttribute() @Test
public void testDecodeUnknownOptionalAttribute()
throws Exception throws Exception
{ {
//unknown attributes //unknown attributes
@ -190,9 +183,8 @@ public class AttributeDecoderTest extends TestCase
Attribute actualReturn = AttributeDecoder.decode( Attribute actualReturn = AttributeDecoder.decode(
bytes, offset, length); bytes, offset, length);
assertEquals( assertEquals(expectedReturn, actualReturn,
"AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute", "AttributeDecoder.decode() failed for a UNKNOWN_OPTIONAL attribute");
expectedReturn, actualReturn);
} }
} }

View File

@ -17,57 +17,47 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Tests the CHANGE-REQUEST attribute class. * Tests the CHANGE-REQUEST attribute class.
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class ChangeRequestAttributeTest extends TestCase public class ChangeRequestAttributeTest
{ {
private ChangeRequestAttribute changeRequestAttribute = null; private ChangeRequestAttribute changeRequestAttribute = null;
private MsgFixture binMessagesFixture; 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(); changeRequestAttribute = new ChangeRequestAttribute();
binMessagesFixture = new MsgFixture(); binMessagesFixture = new MsgFixture();
binMessagesFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
changeRequestAttribute = null; changeRequestAttribute = null;
binMessagesFixture.tearDown();
binMessagesFixture = null; binMessagesFixture = null;
super.tearDown();
} }
/** /**
* Test whether the constructed object has the proper type. * Test whether the constructed object has the proper type.
*/ */
@Test
public void testChangeRequestAttribute() public void testChangeRequestAttribute()
{ {
changeRequestAttribute = new ChangeRequestAttribute(); changeRequestAttribute = new ChangeRequestAttribute();
assertEquals( assertEquals(
"ChangeRequestAttribute did not construct an attribute with the "
+"correct type.",
changeRequestAttribute.getAttributeType(), 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 * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testDecodeAttributeBody() public void testDecodeAttributeBody()
throws StunException throws StunException
{ {
@ -84,27 +75,31 @@ public class ChangeRequestAttributeTest extends TestCase
char length = (char)(attributeValue.length - offset); char length = (char)(attributeValue.length - offset);
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length); changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag", assertEquals(
MsgFixture.CHANGE_IP_FLAG_1, MsgFixture.CHANGE_IP_FLAG_1,
changeRequestAttribute.getChangeIpFlag() changeRequestAttribute.getChangeIpFlag(),
); "decodeAttributeBody() did not properly decode the changeIpFlag"
assertEquals("decodeAttributeBody() did not properly decode the changePortFlag", );
MsgFixture.CHANGE_PORT_FLAG_1, assertEquals(
changeRequestAttribute.getChangePortFlag() MsgFixture.CHANGE_PORT_FLAG_1,
); changeRequestAttribute.getChangePortFlag(),
"decodeAttributeBody() did not properly decode the changePortFlag"
);
//2nd sample //2nd sample
attributeValue = binMessagesFixture.chngReqTestValue2; attributeValue = binMessagesFixture.chngReqTestValue2;
changeRequestAttribute.decodeAttributeBody(attributeValue, offset, length); changeRequestAttribute
assertEquals("decodeAttributeBody() did not properly decode the changeIpFlag", .decodeAttributeBody(attributeValue, offset, length);
MsgFixture.CHANGE_IP_FLAG_2, assertEquals(
changeRequestAttribute.getChangeIpFlag() MsgFixture.CHANGE_IP_FLAG_2,
); changeRequestAttribute.getChangeIpFlag(),
assertEquals("decodeAttributeBody() did not properly decode the changePortFlag", "decodeAttributeBody() did not properly decode the changeIpFlag"
MsgFixture.CHANGE_PORT_FLAG_2, );
changeRequestAttribute.getChangePortFlag() assertEquals(
); MsgFixture.CHANGE_PORT_FLAG_2,
changeRequestAttribute.getChangePortFlag(),
"decodeAttributeBody() did not properly decode the changePortFlag"
);
changeRequestAttribute.getChangePortFlag(); changeRequestAttribute.getChangePortFlag();
} }
@ -112,6 +107,7 @@ public class ChangeRequestAttributeTest extends TestCase
/** /**
* Create sample objects and test whether they encode properly. * Create sample objects and test whether they encode properly.
*/ */
@Test
public void testEncode() public void testEncode()
{ {
byte[] expectedReturn = binMessagesFixture.chngReqTestValue1; byte[] expectedReturn = binMessagesFixture.chngReqTestValue1;
@ -122,8 +118,8 @@ public class ChangeRequestAttributeTest extends TestCase
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1); changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_1);
byte[] actualReturn = changeRequestAttribute.encode(); byte[] actualReturn = changeRequestAttribute.encode();
assertTrue("Object did not encode properly.", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals(expectedReturn, actualReturn)); "Object did not encode properly.");
//2nd test //2nd test
expectedReturn = binMessagesFixture.chngReqTestValue2; expectedReturn = binMessagesFixture.chngReqTestValue2;
@ -133,27 +129,22 @@ public class ChangeRequestAttributeTest extends TestCase
changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2); changeRequestAttribute.setChangePortFlag(MsgFixture.CHANGE_PORT_FLAG_2);
actualReturn = changeRequestAttribute.encode(); actualReturn = changeRequestAttribute.encode();
assertTrue("Object did not encode properly.", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals(expectedReturn, actualReturn)); "Object did not encode properly.");
} }
/** /**
* Tests the equals method against a null, a different and an identical * Tests the equals method against a null, a different and an identical
* object. * object.
*/ */
@Test
public void testEquals() public void testEquals()
{ {
ChangeRequestAttribute target = null;
boolean expectedReturn = false;
//null test //null test
boolean actualReturn = changeRequestAttribute.equals(target); assertNotEquals(changeRequestAttribute, null);
assertEquals("Null value test failed", expectedReturn, actualReturn);
//test against a different object. //test against a different object.
target = new ChangeRequestAttribute(); ChangeRequestAttribute target = new ChangeRequestAttribute();
changeRequestAttribute.setChangeIpFlag(true); changeRequestAttribute.setChangeIpFlag(true);
changeRequestAttribute.setChangePortFlag(false); changeRequestAttribute.setChangePortFlag(false);
@ -161,9 +152,7 @@ public class ChangeRequestAttributeTest extends TestCase
target.setChangeIpFlag(false); target.setChangeIpFlag(false);
target.setChangePortFlag(true); target.setChangePortFlag(true);
actualReturn = changeRequestAttribute.equals(target); assertNotEquals(changeRequestAttribute, target);
assertEquals("Test against a different value failed",
expectedReturn, actualReturn);
//test against an equal value //test against an equal value
target = new ChangeRequestAttribute(); target = new ChangeRequestAttribute();
@ -173,33 +162,27 @@ public class ChangeRequestAttributeTest extends TestCase
target.setChangeIpFlag(true); target.setChangeIpFlag(true);
target.setChangePortFlag(false); target.setChangePortFlag(false);
assertEquals(changeRequestAttribute, target);
expectedReturn = true;
actualReturn = changeRequestAttribute.equals(target);
assertEquals("Test against an equals value failed",
expectedReturn, actualReturn);
} }
/** /**
* Test whether the returned value is always 4. * Test whether the returned value is always 4.
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = 4; // constant 4 bytes of data char expectedReturn = 4; // constant 4 bytes of data
char actualReturn = changeRequestAttribute.getDataLength(); char actualReturn = changeRequestAttribute.getDataLength();
assertEquals("data length returned an invalid value", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "data length returned an invalid value");
} }
/** /**
* Test whether we get a relevant name. * Test whether we get a relevant name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "CHANGE-REQUEST"; assertEquals("CHANGE-REQUEST", changeRequestAttribute.getName());
String actualReturn = changeRequestAttribute.getName();
assertEquals("Invalid name", expectedReturn, actualReturn);
} }
} }

View File

@ -19,10 +19,9 @@ package org.ice4j.attribute;
import org.ice4j.*; import org.ice4j.*;
import java.util.*; import static org.junit.jupiter.api.Assertions.*;
import junit.framework.*;
import org.junit.jupiter.api.*;
/** /**
* Class to test the ConnectionIdAttribute class. * Class to test the ConnectionIdAttribute class.
* *
@ -30,108 +29,86 @@ import junit.framework.*;
* *
*/ */
public class ConnectionIdAttributeTest public class ConnectionIdAttributeTest
extends TestCase
{ {
private ConnectionIdAttribute connectionIdAttribute = null; private ConnectionIdAttribute connectionIdAttribute = null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
@Override @BeforeEach
protected void setUp() throws Exception public void setUp() throws Exception
{ {
super.setUp();
this.connectionIdAttribute = new ConnectionIdAttribute(); this.connectionIdAttribute = new ConnectionIdAttribute();
this.msgFixture = new MsgFixture(); this.msgFixture = new MsgFixture();
msgFixture.setUp();
} }
@Override @AfterEach
protected void tearDown() throws Exception public void tearDown() throws Exception
{ {
this.connectionIdAttribute = null; this.connectionIdAttribute = null;
this.msgFixture.tearDown();
this.msgFixture = null; this.msgFixture = null;
super.tearDown();
} }
/** /**
* Tests whether data length is properly calculated. * Tests whether data length is properly calculated.
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = 4; char expectedReturn = 4;
this.connectionIdAttribute this.connectionIdAttribute
.setConnectionIdValue(MsgFixture.CONNECTION_ID); .setConnectionIdValue(MsgFixture.CONNECTION_ID);
char actualReturn = this.connectionIdAttribute.getDataLength(); char actualReturn = this.connectionIdAttribute.getDataLength();
assertEquals( assertEquals(expectedReturn, actualReturn,
"Datalength is not properly calculated", expectedReturn, "Datalength is not properly calculated");
actualReturn);
} }
/** /**
* Tests getting the name. * Tests getting the name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "CONNECTION-ID"; assertEquals("CONNECTION-ID", connectionIdAttribute.getName());
String actualReturn = connectionIdAttribute.getName();
assertEquals(
"getting name failed", expectedReturn, actualReturn);
} }
/** /**
* Tests the equals method against a null, a different and an identical * Tests the equals method against a null, a different and an identical
* object. * object.
*/ */
@Test
public void testEqualsObject() public void testEqualsObject()
{ {
// null test // null test
ConnectionIdAttribute target = null; assertNotEquals(connectionIdAttribute, null);
boolean expectedReturn = false;
boolean actualReturn = connectionIdAttribute.equals(target);
assertEquals(
"ConnectionIdAttribute.equals() failed against a null target.",
expectedReturn, actualReturn);
// difference test // difference test
target = new ConnectionIdAttribute(); ConnectionIdAttribute target = new ConnectionIdAttribute();
int connectionId = MsgFixture.CONNECTION_ID_2; int connectionId = MsgFixture.CONNECTION_ID_2;
target.setConnectionIdValue(connectionId); target.setConnectionIdValue(connectionId);
connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID); connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID);
expectedReturn = false; assertNotEquals(connectionIdAttribute, target,
actualReturn = connectionIdAttribute.equals(target); "ConnectionIdAttribute.equals() failed against a different target.");
assertEquals(
"ConnectionIdAttribute.equals() failed against a different target.",
expectedReturn, actualReturn);
// equality test // equality test
target.setConnectionIdValue(MsgFixture.CONNECTION_ID); target.setConnectionIdValue(MsgFixture.CONNECTION_ID);
assertEquals(connectionIdAttribute, target,
expectedReturn = true; "ConnectionIdAttribute.equals() failed against an equal target.");
actualReturn = connectionIdAttribute.equals(target);
assertEquals(
"ConnectionIdAttribute.equals() failed against an equal target.",
expectedReturn, actualReturn);
} }
/** /**
* Test whether attributes are properly encoded. * Test whether attributes are properly encoded.
*/ */
@Test
public void testEncode() public void testEncode()
{ {
byte[] expectedReturn = msgFixture.connectionId; byte[] expectedReturn = msgFixture.connectionId;
connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID); connectionIdAttribute.setConnectionIdValue(MsgFixture.CONNECTION_ID);
byte[] actualReturn = connectionIdAttribute.encode(); byte[] actualReturn = connectionIdAttribute.encode();
assertTrue( assertArrayEquals(expectedReturn, actualReturn,
"ConnectionIdAttribute.encode() did not " "ConnectionIdAttribute.encode() did not properly encode a sample attribute");
+ "properly encode a sample attribute", Arrays.equals(
expectedReturn, actualReturn));
} }
/** /**
@ -140,6 +117,7 @@ public class ConnectionIdAttributeTest
* @throws StunException if something goes wrong while decoding * @throws StunException if something goes wrong while decoding
* Attribute Body. * Attribute Body.
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
byte[] attributeValue = msgFixture.connectionId; byte[] attributeValue = msgFixture.connectionId;
@ -150,31 +128,31 @@ public class ConnectionIdAttributeTest
attributeValue, offset, length); attributeValue, offset, length);
assertEquals( assertEquals(
"ConnectionIdAttribute.decode() did not properly decode the " MsgFixture.CONNECTION_ID,
+ "connection id field.", MsgFixture.CONNECTION_ID, connectionIdAttribute.getConnectionIdValue(),
connectionIdAttribute.getConnectionIdValue()); "ConnectionIdAttribute.decode() did not properly decode the connection id field."
);
} }
/** /**
* Tests that the connection Id is always integer. * Tests that the connection Id is always integer.
*/ */
@Test
public void testGetConnectionIdValue() public void testGetConnectionIdValue()
{ {
int expectedReturn = 0x5555; int expectedReturn = 0x5555;
this.connectionIdAttribute this.connectionIdAttribute
.setConnectionIdValue(MsgFixture.CONNECTION_ID); .setConnectionIdValue(MsgFixture.CONNECTION_ID);
int actualReturn = this.connectionIdAttribute.getConnectionIdValue(); int actualReturn = this.connectionIdAttribute.getConnectionIdValue();
assertEquals( assertEquals(expectedReturn, actualReturn,
"ConnectionId is not properly calculated", expectedReturn, "ConnectionId is not properly calculated");
actualReturn);
expectedReturn = 0x2222; expectedReturn = 0x2222;
this.connectionIdAttribute this.connectionIdAttribute
.setConnectionIdValue(MsgFixture.CONNECTION_ID_2); .setConnectionIdValue(MsgFixture.CONNECTION_ID_2);
actualReturn = this.connectionIdAttribute.getConnectionIdValue(); actualReturn = this.connectionIdAttribute.getConnectionIdValue();
assertEquals( assertEquals(expectedReturn, actualReturn,
"ConnectionId is not properly calculated", expectedReturn, "ConnectionId is not properly calculated");
actualReturn);
} }
} }

View File

@ -17,51 +17,44 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class ErrorCodeAttributeTest extends TestCase { public class ErrorCodeAttributeTest
{
private ErrorCodeAttribute errorCodeAttribute = null; private ErrorCodeAttribute errorCodeAttribute = null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
public ErrorCodeAttributeTest(String name) { @BeforeEach
super(name); public void setUp() throws Exception
} {
protected void setUp() throws Exception {
super.setUp();
errorCodeAttribute = new ErrorCodeAttribute(); errorCodeAttribute = new ErrorCodeAttribute();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
msgFixture.setUp();
} }
protected void tearDown() throws Exception { @AfterEach
public void tearDown() throws Exception {
errorCodeAttribute = null; errorCodeAttribute = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Test Attribute type * Test Attribute type
*/ */
@Test
public void testErrorCodeAttribute() public void testErrorCodeAttribute()
{ {
errorCodeAttribute = new ErrorCodeAttribute(); errorCodeAttribute = new ErrorCodeAttribute();
assertEquals(
assertEquals("ErrorCodeAttribute() constructed an attribute with an invalid type", Attribute.ERROR_CODE,
Attribute.ERROR_CODE, errorCodeAttribute.getAttributeType(),
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 * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testDecodeAttributeBody() public void testDecodeAttributeBody()
throws StunException { throws StunException {
byte[] attributeValue = msgFixture.errCodeTestValue; byte[] attributeValue = msgFixture.errCodeTestValue;
@ -76,18 +70,22 @@ public class ErrorCodeAttributeTest extends TestCase {
char length = (char)(attributeValue.length - Attribute.HEADER_LENGTH); char length = (char)(attributeValue.length - Attribute.HEADER_LENGTH);
errorCodeAttribute.decodeAttributeBody(attributeValue, offset, length); errorCodeAttribute.decodeAttributeBody(attributeValue, offset, length);
assertEquals("Error Class was not correctly decoded", assertEquals(
MsgFixture.ERROR_CLASS, MsgFixture.ERROR_CLASS,
errorCodeAttribute.getErrorClass()); errorCodeAttribute.getErrorClass(),
"Error Class was not correctly decoded"
);
assertEquals("Error Number was not correctly decoded", assertEquals(
MsgFixture.ERROR_NUMBER, MsgFixture.ERROR_NUMBER,
errorCodeAttribute.getErrorNumber()); errorCodeAttribute.getErrorNumber(),
"Error Number was not correctly decoded"
assertEquals("Reason phrase was not correctly decoded", );
MsgFixture.REASON_PHRASE.trim(),
errorCodeAttribute.getReasonPhrase().trim());
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 * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testEncode() public void testEncode()
throws StunException throws StunException
{ {
@ -108,8 +107,8 @@ public class ErrorCodeAttributeTest extends TestCase {
byte[] actualReturn = errorCodeAttribute.encode(); byte[] actualReturn = errorCodeAttribute.encode();
assertTrue("encode() did not return the expected binary array.", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( 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 * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testEquals() public void testEquals()
throws StunException throws StunException
{ {
//null value test //null value test
ErrorCodeAttribute target = null; assertNotEquals(errorCodeAttribute, null,
boolean expectedReturn = false; "equals() failed against a null value target.");
boolean actualReturn = errorCodeAttribute.equals(target);
assertEquals("equals() failed against a null value target.",
expectedReturn, actualReturn);
//different objects //different objects
ErrorCodeAttribute target;
target = new ErrorCodeAttribute(); target = new ErrorCodeAttribute();
expectedReturn = false;
target.setErrorClass(MsgFixture.ERROR_CLASS); target.setErrorClass(MsgFixture.ERROR_CLASS);
target.setErrorNumber(MsgFixture.ERROR_NUMBER); target.setErrorNumber(MsgFixture.ERROR_NUMBER);
@ -139,14 +135,12 @@ public class ErrorCodeAttributeTest extends TestCase {
errorCodeAttribute.setErrorClass((byte)(MsgFixture.ERROR_CLASS+1)); errorCodeAttribute.setErrorClass((byte)(MsgFixture.ERROR_CLASS+1));
errorCodeAttribute.setErrorNumber((byte)(MsgFixture.ERROR_NUMBER+1)); errorCodeAttribute.setErrorNumber((byte)(MsgFixture.ERROR_NUMBER+1));
actualReturn = errorCodeAttribute.equals(target); assertNotEquals(errorCodeAttribute, target,
assertEquals("equals() failed against a not equal target.", "equals() failed against a not equal target.");
expectedReturn, actualReturn);
//different objects //equal objects
target = new ErrorCodeAttribute(); target = new ErrorCodeAttribute();
errorCodeAttribute = new ErrorCodeAttribute(); errorCodeAttribute = new ErrorCodeAttribute();
expectedReturn = true;
target.setErrorClass(MsgFixture.ERROR_CLASS); target.setErrorClass(MsgFixture.ERROR_CLASS);
target.setErrorNumber(MsgFixture.ERROR_NUMBER); target.setErrorNumber(MsgFixture.ERROR_NUMBER);
@ -154,11 +148,8 @@ public class ErrorCodeAttributeTest extends TestCase {
errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS); errorCodeAttribute.setErrorClass(MsgFixture.ERROR_CLASS);
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER); errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
actualReturn = errorCodeAttribute.equals(target); assertEquals(errorCodeAttribute, target,
assertEquals("equals() failed against a not equal target.", "equals() failed against an equal target.");
expectedReturn, actualReturn);
} }
/** /**
@ -166,6 +157,7 @@ public class ErrorCodeAttributeTest extends TestCase {
* *
* @throws StunException java.lang.Exception if we fail * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
throws StunException throws StunException
{ {
@ -177,16 +169,14 @@ public class ErrorCodeAttributeTest extends TestCase {
errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE); errorCodeAttribute.setReasonPhrase(MsgFixture.REASON_PHRASE);
char actualReturn = errorCodeAttribute.getDataLength(); 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 * Test whether error code is properly calculated from error class and number
*
* @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testGetErrorCode() public void testGetErrorCode()
throws StunException
{ {
char expectedReturn = (char)(100*MsgFixture.ERROR_CLASS char expectedReturn = (char)(100*MsgFixture.ERROR_CLASS
+ MsgFixture.ERROR_NUMBER); + MsgFixture.ERROR_NUMBER);
@ -195,35 +185,36 @@ public class ErrorCodeAttributeTest extends TestCase {
errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER); errorCodeAttribute.setErrorNumber(MsgFixture.ERROR_NUMBER);
char actualReturn = errorCodeAttribute.getErrorCode(); char actualReturn = errorCodeAttribute.getErrorCode();
assertEquals("return value", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
/** /**
* Test whether we get a proper name for that attribute. * Test whether we get a proper name for that attribute.
*/ */
@Test
public void testGetName() { public void testGetName() {
String expectedReturn = "ERROR-CODE"; assertEquals("ERROR-CODE", errorCodeAttribute.getName());
String actualReturn = errorCodeAttribute.getName();
assertEquals("return value", expectedReturn, actualReturn);
} }
/** /**
* Test whether error code is properly calculated from error class and number * 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); char errorCode = (char)(MsgFixture.ERROR_CLASS*100 + MsgFixture.ERROR_NUMBER);
errorCodeAttribute.setErrorCode(errorCode); errorCodeAttribute.setErrorCode(errorCode);
assertEquals("An error class was not properly set after decoding an error code.", assertEquals(
(int)MsgFixture.ERROR_CLASS, MsgFixture.ERROR_CLASS,
(int)errorCodeAttribute.getErrorClass()); (int) errorCodeAttribute.getErrorClass(),
assertEquals("An error number was not properly set after decoding an error code.", "An error class was not properly set after decoding an error code."
(int)MsgFixture.ERROR_NUMBER, );
(int)errorCodeAttribute.getErrorNumber()); assertEquals(
MsgFixture.ERROR_NUMBER,
(int) errorCodeAttribute.getErrorNumber(),
"An error number was not properly set after decoding an error code."
);
} }
} }

View File

@ -17,19 +17,17 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Tests the nonce attribute class. * Tests the nonce attribute class.
* *
* @author Emil Ivov * @author Emil Ivov
* @author Sebastien Vincent * @author Sebastien Vincent
*/ */
public class NonceAttributeTest extends TestCase public class NonceAttributeTest
{ {
private NonceAttribute nonceAttribute = null; private NonceAttribute nonceAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -40,30 +38,26 @@ public class NonceAttributeTest extends TestCase
0, (byte)nonceValue.length(), 0, (byte)nonceValue.length(),
'0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; '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(); msgFixture = new MsgFixture();
nonceAttribute = new NonceAttribute(); nonceAttribute = new NonceAttribute();
nonceAttribute.setNonce(nonceValue.getBytes()); nonceAttribute.setNonce(nonceValue.getBytes());
msgFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
nonceAttribute = null; nonceAttribute = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Tests decoding of the nonce attribute. * Tests decoding of the nonce attribute.
* @throws StunException upon a failure * @throws StunException upon a failure
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
char offset = 0; char offset = 0;
@ -72,63 +66,63 @@ public class NonceAttributeTest extends TestCase
decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length); decoded.decodeAttributeBody(nonceValue.getBytes(), offset, length);
//nonce value //nonce value
assertEquals( "decode failed", nonceAttribute, decoded); assertEquals(nonceAttribute, decoded, "decode failed");
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertTrue("encode failed", assertArrayEquals(nonceAttribute.encode(), attributeBinValue,
Arrays.equals(nonceAttribute.encode(), "encode failed");
attributeBinValue));
} }
/** /**
* Test Equals * Test Equals
*/ */
@Test
public void testEquals() public void testEquals()
{ {
NonceAttribute nonceAttribute2 = new NonceAttribute(); NonceAttribute nonceAttribute2 = new NonceAttribute();
nonceAttribute2.setNonce(nonceValue.getBytes()); nonceAttribute2.setNonce(nonceValue.getBytes());
//test positive equals //test positive equals
assertEquals("testequals failed", nonceAttribute, nonceAttribute2); assertEquals(nonceAttribute, nonceAttribute2);
//test negative equals //test negative equals
nonceAttribute2 = new NonceAttribute(); nonceAttribute2 = new NonceAttribute();
nonceAttribute2.setNonce("some other nonce".getBytes()); nonceAttribute2.setNonce("some other nonce".getBytes());
//test positive equals //test positive equals
assertFalse("testequals failed", assertNotEquals(nonceAttribute2, nonceAttribute);
nonceAttribute.equals(nonceAttribute2));
//test null equals //test null equals
assertFalse("testequals failed", assertNotEquals(nonceAttribute, null);
nonceAttribute.equals(null));
} }
/** /**
* Tests extracting data length * Tests extracting data length
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = (char)nonceValue.length(); char expectedReturn = (char)nonceValue.length();
char actualReturn = nonceAttribute.getDataLength(); char actualReturn = nonceAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "NONCE"; assertEquals("NONCE", nonceAttribute.getName());
String actualReturn = nonceAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
} }
@Test
public void testSetGetNonce() public void testSetGetNonce()
{ {
byte[] expectedReturn = nonceValue.getBytes(); byte[] expectedReturn = nonceValue.getBytes();
@ -137,8 +131,7 @@ public class NonceAttributeTest extends TestCase
att.setNonce(expectedReturn); att.setNonce(expectedReturn);
byte[] actualReturn = att.getNonce(); byte[] actualReturn = att.getNonce();
assertTrue("nonce setter or getter failed", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( expectedReturn, "nonce setter or getter failed");
actualReturn));
} }
} }

View File

@ -17,25 +17,22 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.Arrays;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* @author Emil Ivov * @author Emil Ivov
*/ */
public class OptionalAttributeAttributeTest extends TestCase public class OptionalAttributeAttributeTest
{ {
private OptionalAttribute optionalAttribute = null; private OptionalAttribute optionalAttribute = null;
private MsgFixture msgFixture = null; private MsgFixture msgFixture = null;
byte[] expectedAttributeValue = null; byte[] expectedAttributeValue = null;
protected void setUp() throws Exception @BeforeEach
public void setUp() throws Exception
{ {
super.setUp();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
int offset = Attribute.HEADER_LENGTH; int offset = Attribute.HEADER_LENGTH;
@ -51,17 +48,18 @@ public class OptionalAttributeAttributeTest extends TestCase
msgFixture.optionalAttributeType); msgFixture.optionalAttributeType);
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
optionalAttribute = null; optionalAttribute = null;
expectedAttributeValue = null; expectedAttributeValue = null;
super.tearDown();
} }
/** /**
* Test whether sample binary arrays are correctly decoded. * Test whether sample binary arrays are correctly decoded.
* @throws StunException if anything goes wrong. * @throws StunException if anything goes wrong.
*/ */
@Test
public void testDecodeAttributeBody() throws StunException { public void testDecodeAttributeBody() throws StunException {
char offset = Attribute.HEADER_LENGTH; char offset = Attribute.HEADER_LENGTH;
@ -70,60 +68,52 @@ public class OptionalAttributeAttributeTest extends TestCase
optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute, optionalAttribute.decodeAttributeBody(msgFixture.unknownOptionalAttribute,
offset, length); offset, length);
assertArrayEquals(
expectedAttributeValue, optionalAttribute.getBody(),
"OptionalAttribute did not decode properly.");
assertTrue("OptionalAttribute did not decode properly.", assertEquals(length, optionalAttribute.getDataLength(),
Arrays.equals( expectedAttributeValue, "Length was not properly decoded");
optionalAttribute.getBody()));
assertEquals("Lenght was not properly decoded", length,
optionalAttribute.getDataLength());
} }
/** /**
* Test whether attributes are properly encoded * Test whether attributes are properly encoded
*/ */
@Test
public void testEncode() public void testEncode()
{ {
optionalAttribute.setBody(expectedAttributeValue, 0, optionalAttribute.setBody(expectedAttributeValue, 0,
expectedAttributeValue.length); expectedAttributeValue.length);
byte[] actualReturn = optionalAttribute.encode(); byte[] actualReturn = optionalAttribute.encode();
assertArrayEquals(msgFixture.unknownOptionalAttribute, actualReturn);
assertTrue("encode failed",
Arrays.equals( msgFixture.unknownOptionalAttribute, actualReturn) );
} }
/** /**
* Test whether the equals method works ok * Test whether the equals method works ok
*/ */
@Test
public void testEquals() public void testEquals()
{ {
//null comparison //null comparison
Object obj = null;
boolean expectedReturn = false;
optionalAttribute.setBody( expectedAttributeValue, 0, optionalAttribute.setBody( expectedAttributeValue, 0,
expectedAttributeValue.length); expectedAttributeValue.length);
boolean actualReturn = optionalAttribute.equals(obj); assertNotEquals(optionalAttribute, null);
assertEquals("failed null comparison", expectedReturn, actualReturn);
//wrong type comparison //wrong type comparison
obj = "hehe :)"; assertNotEquals(optionalAttribute, "hehe :)");
actualReturn = optionalAttribute.equals(obj);
assertEquals("failed wrong type comparison", expectedReturn,
actualReturn);
//succesful comparison //succesful comparison
obj = new OptionalAttribute(msgFixture.optionalAttributeType); OptionalAttribute obj =
new OptionalAttribute(msgFixture.optionalAttributeType);
((OptionalAttribute)obj).setBody( expectedAttributeValue, 0, obj.setBody( expectedAttributeValue, 0,
expectedAttributeValue.length); expectedAttributeValue.length);
expectedReturn = true; assertEquals(obj, optionalAttribute);
actualReturn = optionalAttribute.equals(obj);
assertEquals("failed null comparison", expectedReturn, actualReturn);
} }
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = (char)expectedAttributeValue.length; char expectedReturn = (char)expectedAttributeValue.length;
@ -132,7 +122,7 @@ public class OptionalAttributeAttributeTest extends TestCase
expectedAttributeValue.length); expectedAttributeValue.length);
char actualReturn = optionalAttribute.getDataLength(); char actualReturn = optionalAttribute.getDataLength();
assertEquals("return value", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
} }

View File

@ -17,19 +17,17 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Tests the realm attribute class. * Tests the realm attribute class.
* *
* @author Emil Ivov * @author Emil Ivov
* @author Sebastien Vincent * @author Sebastien Vincent
*/ */
public class RealmAttributeTest extends TestCase public class RealmAttributeTest
{ {
private RealmAttribute realmAttribute = null; private RealmAttribute realmAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -40,30 +38,27 @@ public class RealmAttributeTest extends TestCase
0, (byte)realmValue.length(), 0, (byte)realmValue.length(),
'd', 'o', 'm', 'a', 'i', 'n', '.', 'o', 'r', 'g', 0x00, 0x00}; '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(); msgFixture = new MsgFixture();
realmAttribute = new RealmAttribute(); realmAttribute = new RealmAttribute();
realmAttribute.setRealm(realmValue.getBytes()); realmAttribute.setRealm(realmValue.getBytes());
msgFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
realmAttribute = null; realmAttribute = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Tests decoding of the realm attribute. * Tests decoding of the realm attribute.
* @throws StunException upon a failure * @throws StunException upon a failure
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
char offset = 0; char offset = 0;
@ -72,63 +67,62 @@ public class RealmAttributeTest extends TestCase
decoded.decodeAttributeBody(realmValue.getBytes(), offset, length); decoded.decodeAttributeBody(realmValue.getBytes(), offset, length);
//realm value //realm value
assertEquals( "decode failed", realmAttribute, decoded); assertEquals(realmAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertTrue("encode failed", assertArrayEquals(realmAttribute.encode(), attributeBinValue);
Arrays.equals(realmAttribute.encode(),
attributeBinValue));
} }
/** /**
* Test Equals * Test Equals
*/ */
@Test
public void testEquals() public void testEquals()
{ {
RealmAttribute realmAttribute2 = new RealmAttribute(); RealmAttribute realmAttribute2 = new RealmAttribute();
realmAttribute2.setRealm(realmValue.getBytes()); realmAttribute2.setRealm(realmValue.getBytes());
//test positive equals //test positive equals
assertEquals("testequals failed", realmAttribute, realmAttribute2); assertEquals(realmAttribute, realmAttribute2);
//test negative equals //test negative equals
realmAttribute2 = new RealmAttribute(); realmAttribute2 = new RealmAttribute();
realmAttribute2.setRealm("some other realm".getBytes()); realmAttribute2.setRealm("some other realm".getBytes());
//test positive equals //test positive equals
assertFalse("testequals failed", assertNotEquals(realmAttribute2, realmAttribute);
realmAttribute.equals(realmAttribute2));
//test null equals //test null equals
assertFalse("testequals failed", assertNotEquals(realmAttribute, null);
realmAttribute.equals(null));
} }
/** /**
* Tests extracting data length * Tests extracting data length
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = (char)realmValue.length(); char expectedReturn = (char)realmValue.length();
char actualReturn = realmAttribute.getDataLength(); char actualReturn = realmAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "REALM"; assertEquals("REALM", realmAttribute.getName());
String actualReturn = realmAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
} }
@Test
public void testSetGetRealm() public void testSetGetRealm()
{ {
byte[] expectedReturn = realmValue.getBytes(); byte[] expectedReturn = realmValue.getBytes();
@ -137,8 +131,7 @@ public class RealmAttributeTest extends TestCase
att.setRealm(expectedReturn); att.setRealm(expectedReturn);
byte[] actualReturn = att.getRealm(); byte[] actualReturn = att.getRealm();
assertTrue("realm setter or getter failed", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( expectedReturn, "realm setter or getter failed");
actualReturn));
} }
} }

View File

@ -17,12 +17,10 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import java.util.*; import static org.junit.jupiter.api.Assertions.*;
import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Class to test the RequestedAddressFamilyAttribute class. * Class to test the RequestedAddressFamilyAttribute class.
* *
@ -30,42 +28,31 @@ import org.ice4j.*;
* *
*/ */
public class RequestedAddressFamilyAttributeTest public class RequestedAddressFamilyAttributeTest
extends TestCase
{ {
private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute = private RequestedAddressFamilyAttribute requestedAddressFamilyAttribute =
null; null;
private MsgFixture msgFixture; private MsgFixture msgFixture;
@Override @BeforeEach
protected void setUp() throws Exception public void setUp() throws Exception
{ {
super.setUp();
this.requestedAddressFamilyAttribute = this.requestedAddressFamilyAttribute =
new RequestedAddressFamilyAttribute(); new RequestedAddressFamilyAttribute();
this.msgFixture = new MsgFixture(); this.msgFixture = new MsgFixture();
msgFixture.setUp();
} }
public RequestedAddressFamilyAttributeTest(String name) @AfterEach
{ public void tearDown() throws Exception
super(name);
}
@Override
protected void tearDown() throws Exception
{ {
this.requestedAddressFamilyAttribute = null; this.requestedAddressFamilyAttribute = null;
this.msgFixture.tearDown();
this.msgFixture = null; this.msgFixture = null;
super.tearDown();
} }
/** /**
* Tests whether data length is properly calculated. * Tests whether data length is properly calculated.
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = 1; char expectedReturn = 1;
@ -73,47 +60,39 @@ public class RequestedAddressFamilyAttributeTest
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
char actualReturn = char actualReturn =
this.requestedAddressFamilyAttribute.getDataLength(); this.requestedAddressFamilyAttribute.getDataLength();
assertEquals( assertEquals(expectedReturn, actualReturn,
"Datalength is not properly calculated", expectedReturn, "Datalength is not properly calculated");
actualReturn);
expectedReturn = 1; expectedReturn = 1;
this.requestedAddressFamilyAttribute this.requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
actualReturn = this.requestedAddressFamilyAttribute.getDataLength(); actualReturn = this.requestedAddressFamilyAttribute.getDataLength();
assertEquals( assertEquals(expectedReturn, actualReturn,
"Datalength is not properly calculated", expectedReturn, "Datalength is not properly calculated");
actualReturn);
} }
/** /**
* Tests getting the name. * Tests getting the name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "REQUESTED-ADDRESS-FAMILY"; assertEquals("REQUESTED-ADDRESS-FAMILY", requestedAddressFamilyAttribute.getName());
String actualReturn = requestedAddressFamilyAttribute.getName();
assertEquals(
"getting name failed", expectedReturn, actualReturn);
} }
/** /**
* Tests the equals method against a null, a different and an identical * Tests the equals method against a null, a different and an identical
* object. * object.
*/ */
@Test
public void testEqualsObject() public void testEqualsObject()
{ {
// null test // null test
RequestedAddressFamilyAttribute target = null; assertNotEquals(requestedAddressFamilyAttribute, null);
boolean expectedReturn = false;
boolean actualReturn = requestedAddressFamilyAttribute.equals(target);
assertEquals(
"RequestedAddressFamilyAttribute.equals() failed against a null "
+ "target.", expectedReturn, actualReturn);
// difference test // difference test
RequestedAddressFamilyAttribute target;
target = new RequestedAddressFamilyAttribute(); target = new RequestedAddressFamilyAttribute();
char family = MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6; char family = MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6;
@ -122,20 +101,12 @@ public class RequestedAddressFamilyAttributeTest
requestedAddressFamilyAttribute requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
expectedReturn = false; assertNotEquals(requestedAddressFamilyAttribute, target);
actualReturn = requestedAddressFamilyAttribute.equals(target);
assertEquals(
"RequestedAddressFamilyAttribute.equals() failed against a "
+ "different target.", expectedReturn, actualReturn);
// equality test // equality test
target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
expectedReturn = true; assertEquals(requestedAddressFamilyAttribute, target);
actualReturn = requestedAddressFamilyAttribute.equals(target);
assertEquals(
"RequestedAddressFamilyAttribute.equals() failed against an equal "
+ "target.", expectedReturn, actualReturn);
// ipv6 equality test // ipv6 equality test
target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); target.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
@ -143,11 +114,7 @@ public class RequestedAddressFamilyAttributeTest
requestedAddressFamilyAttribute requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
expectedReturn = true; assertEquals(requestedAddressFamilyAttribute, target);
actualReturn = requestedAddressFamilyAttribute.equals(target);
assertEquals(
"RequestedAddressFamilyAttribute.equals() failed for IPv6 address.",
expectedReturn, actualReturn);
} }
/** /**
@ -156,6 +123,7 @@ public class RequestedAddressFamilyAttributeTest
* @throws StunException if something goes wrong while decoding * @throws StunException if something goes wrong while decoding
* Attribute Body. * Attribute Body.
*/ */
@Test
public void testDecodeAttributeBodyV4() throws StunException public void testDecodeAttributeBodyV4() throws StunException
{ {
byte[] attributeValue = msgFixture.requestedAddressFamilyV4; byte[] attributeValue = msgFixture.requestedAddressFamilyV4;
@ -166,10 +134,10 @@ public class RequestedAddressFamilyAttributeTest
attributeValue, offset, length); attributeValue, offset, length);
assertEquals( assertEquals(
"RequestedAddressFamilyAttribute.decode() did not properly decode "
+ "the family field.",
MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4, 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 * @throws StunException if something goes wrong while decoding
* Attribute Body. * Attribute Body.
*/ */
public void testDecodeAttributeBodyV6() throws StunException @Test
public void testDecodeAttributeBodyV6() throws StunException
{ {
byte[] attributeValue = msgFixture.requestedAddressFamilyV6; byte[] attributeValue = msgFixture.requestedAddressFamilyV6;
char offset = Attribute.HEADER_LENGTH; char offset = Attribute.HEADER_LENGTH;
@ -188,63 +157,62 @@ public class RequestedAddressFamilyAttributeTest
attributeValue, offset, length); attributeValue, offset, length);
assertEquals( assertEquals(
"RequestedAddressFamilyAttribute.decode() did not properly decode.",
MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6, MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6,
requestedAddressFamilyAttribute.getFamily()); requestedAddressFamilyAttribute.getFamily(),
"RequestedAddressFamilyAttribute.decode() did not properly decode."
);
} }
/** /**
* Test whether attributes are properly encoded. * Test whether attributes are properly encoded.
*/ */
@Test
public void testEncodeV4() public void testEncodeV4()
{ {
byte[] expectedReturn = msgFixture.requestedAddressFamilyV4; byte[] expectedReturn = msgFixture.requestedAddressFamilyV4;
requestedAddressFamilyAttribute requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
byte[] actualReturn = requestedAddressFamilyAttribute.encode(); byte[] actualReturn = requestedAddressFamilyAttribute.encode();
assertTrue( assertArrayEquals(
"RequestedAddressFamilyAttribute.encode() did not " expectedReturn, actualReturn,
+ "properly encode a sample attribute for IPv4 family", "RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv4 family"
Arrays.equals( );
expectedReturn, actualReturn));
} }
/** /**
* Test whether attributes are properly encoded. * Test whether attributes are properly encoded.
*/ */
@Test
public void testEncodeV6() public void testEncodeV6()
{ {
byte[] expectedReturn = msgFixture.requestedAddressFamilyV6; byte[] expectedReturn = msgFixture.requestedAddressFamilyV6;
requestedAddressFamilyAttribute requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
byte[] actualReturn = requestedAddressFamilyAttribute.encode(); byte[] actualReturn = requestedAddressFamilyAttribute.encode();
assertTrue( assertArrayEquals(
"RequestedAddressFamilyAttribute.encode() did not " expectedReturn, actualReturn,
+ "properly encode a sample attribute for IPv6 family", "RequestedAddressFamilyAttribute.encode() did not properly encode a sample attribute for IPv6 family"
Arrays.equals( );
expectedReturn, actualReturn));
} }
/** /**
* Tests that the address family is always 0x01 or 0x02. * Tests that the address family is always 0x01 or 0x02.
*/ */
@Test
public void testGetFamily() public void testGetFamily()
{ {
char expectedReturn = 0x01; char expectedReturn = 0x01;
this.requestedAddressFamilyAttribute this.requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V4);
char actualReturn = this.requestedAddressFamilyAttribute.getFamily(); char actualReturn = this.requestedAddressFamilyAttribute.getFamily();
assertEquals( assertEquals(expectedReturn, actualReturn,
"Family is not properly calculated", expectedReturn, "Family is not properly calculated");
actualReturn);
expectedReturn = 0x02; expectedReturn = 0x02;
this.requestedAddressFamilyAttribute this.requestedAddressFamilyAttribute
.setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6); .setFamily(MsgFixture.REQUESTED_ADDRESS_FAMILY_ATTRIBUTE_V6);
actualReturn = this.requestedAddressFamilyAttribute.getFamily(); actualReturn = this.requestedAddressFamilyAttribute.getFamily();
assertEquals( assertEquals(expectedReturn, actualReturn,
"Family is not properly calculated", expectedReturn, "Family is not properly calculated");
actualReturn);
} }
} }

View File

@ -17,18 +17,16 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Tests the software attribute class. * Tests the software attribute class.
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class SoftwareAttributeTest extends TestCase public class SoftwareAttributeTest
{ {
private SoftwareAttribute softwareAttribute = null; private SoftwareAttribute softwareAttribute = null;
MsgFixture msgFixture = 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', 't', 'u', 'r', 'n', 's', 'e', 'r','v', 'e', 'r', '.', 'o', 'r', 'g',
0x00, 0x00}; 0x00, 0x00};
protected void setUp() throws Exception @BeforeEach
public void setUp() throws Exception
{ {
super.setUp();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
softwareAttribute = new SoftwareAttribute(); softwareAttribute = new SoftwareAttribute();
softwareAttribute.setSoftware(softwareValue.getBytes()); softwareAttribute.setSoftware(softwareValue.getBytes());
msgFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
softwareAttribute = null; softwareAttribute = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Tests decoding of the software attribute. * Tests decoding of the software attribute.
* @throws StunException upon a failure * @throws StunException upon a failure
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
char offset = 0; char offset = 0;
@ -72,63 +67,62 @@ public class SoftwareAttributeTest extends TestCase
decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length); decoded.decodeAttributeBody(softwareValue.getBytes(), offset, length);
//software value //software value
assertEquals( "decode failed", softwareAttribute, decoded); assertEquals(softwareAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertTrue("encode failed", assertArrayEquals(softwareAttribute.encode(), attributeBinValue);
Arrays.equals(softwareAttribute.encode(),
attributeBinValue));
} }
/** /**
* Test Equals * Test Equals
*/ */
@Test
public void testEquals() public void testEquals()
{ {
SoftwareAttribute softwareAttribute2 = new SoftwareAttribute(); SoftwareAttribute softwareAttribute2 = new SoftwareAttribute();
softwareAttribute2.setSoftware(softwareValue.getBytes()); softwareAttribute2.setSoftware(softwareValue.getBytes());
//test positive equals //test positive equals
assertEquals("testequals failed", softwareAttribute, softwareAttribute2); assertEquals(softwareAttribute, softwareAttribute2);
//test negative equals //test negative equals
softwareAttribute2 = new SoftwareAttribute(); softwareAttribute2 = new SoftwareAttribute();
softwareAttribute2.setSoftware("some other software".getBytes()); softwareAttribute2.setSoftware("some other software".getBytes());
//test positive equals //test positive equals
assertFalse("testequals failed", assertNotEquals(softwareAttribute2, softwareAttribute);
softwareAttribute.equals(softwareAttribute2));
//test null equals //test null equals
assertFalse("testequals failed", assertNotEquals(softwareAttribute, null);
softwareAttribute.equals(null));
} }
/** /**
* Tests extracting data length * Tests extracting data length
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = (char)softwareValue.length(); char expectedReturn = (char)softwareValue.length();
char actualReturn = softwareAttribute.getDataLength(); char actualReturn = softwareAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "SOFTWARE"; assertEquals("SOFTWARE", softwareAttribute.getName());
String actualReturn = softwareAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
} }
@Test
public void testSetGetSoftware() public void testSetGetSoftware()
{ {
byte[] expectedReturn = softwareValue.getBytes(); byte[] expectedReturn = softwareValue.getBytes();
@ -137,8 +131,7 @@ public class SoftwareAttributeTest extends TestCase
att.setSoftware(expectedReturn); att.setSoftware(expectedReturn);
byte[] actualReturn = att.getSoftware(); byte[] actualReturn = att.getSoftware();
assertTrue("software setter or getter failed", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( expectedReturn, "software setter or getter failed");
actualReturn));
} }
} }

View File

@ -17,58 +17,49 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.*; import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Tests the UNKNOWN attribute class. * Tests the UNKNOWN attribute class.
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class UnknownAttributesAttributeTest extends TestCase public class UnknownAttributesAttributeTest
{ {
private UnknownAttributesAttribute unknownAttributesAttribute = null; private UnknownAttributesAttribute unknownAttributesAttribute = null;
private MsgFixture binMessagesFixture; 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(); unknownAttributesAttribute = new UnknownAttributesAttribute();
binMessagesFixture = new MsgFixture(); binMessagesFixture = new MsgFixture();
binMessagesFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
unknownAttributesAttribute = null; unknownAttributesAttribute = null;
binMessagesFixture.tearDown();
binMessagesFixture = null; binMessagesFixture = null;
super.tearDown();
} }
//-------------------------------- TESTS --------------------------------------- //-------------------------------- TESTS ---------------------------------------
/** /**
* Verify the the constructed object has the correct (UNKNOWN-ATTRIBUTES) * Verify the the constructed object has the correct (UNKNOWN-ATTRIBUTES)
* type. * type.
*/ */
@Test
public void testUnknownAttributesAttribute() public void testUnknownAttributesAttribute()
{ {
unknownAttributesAttribute = new UnknownAttributesAttribute(); unknownAttributesAttribute = new UnknownAttributesAttribute();
assertEquals(
assertEquals("UnknownAttributesAttribute() did not properly set the " Attribute.UNKNOWN_ATTRIBUTES,
+"Attribute's type field!", (int) unknownAttributesAttribute.getAttributeType(),
(int)Attribute.UNKNOWN_ATTRIBUTES, "UnknownAttributesAttribute() did not properly set the Attribute's type field!"
(int)unknownAttributesAttribute.getAttributeType() );
);
} }
/** /**
@ -76,37 +67,40 @@ public class UnknownAttributesAttributeTest extends TestCase
* and that a second addition of the same id would not augment the attribute * and that a second addition of the same id would not augment the attribute
* count. * count.
*/ */
@Test
public void testAddAttributeID() public void testAddAttributeID()
{ {
char attributeID = 0x22; // unknown attribute id char attributeID = 0x22; // unknown attribute id
unknownAttributesAttribute.addAttributeID(attributeID); unknownAttributesAttribute.addAttributeID(attributeID);
assertEquals("addAttributeID does not seem to properly add the attribute ID", assertEquals(
(int)attributeID, (int) attributeID,
(int)unknownAttributesAttribute.getAttribute(0) (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", assertEquals(
1, 1,
unknownAttributesAttribute.getAttributeCount() unknownAttributesAttribute.getAttributeCount(),
); "addAttributeID does not seem to properly add the attribute ID"
);
//add a second one //add a second one
unknownAttributesAttribute.addAttributeID(attributeID); unknownAttributesAttribute.addAttributeID(attributeID);
assertEquals("Adding a 2nd time the same attributeID should not change " assertEquals(
+"the number of attributes", 1,
1, unknownAttributesAttribute.getAttributeCount(),
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. * Tests whether a sample binary array is properly decoded.
* @throws StunException if anything goes wrong. * @throws StunException if anything goes wrong.
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
//a copy of the array in the fixture: //a copy of the array in the fixture:
@ -118,37 +112,44 @@ public class UnknownAttributesAttributeTest extends TestCase
- Attribute.HEADER_LENGTH)); - Attribute.HEADER_LENGTH));
//is every one there? //is every one there?
assertTrue( assertTrue(
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_1ST_ATT +" attribute id "
+ "was not found after decoding a binary array that contained it.",
unknownAttributesAttribute.contains( 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( assertTrue(
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT +" attribute id "
+ "was not found after decoding a binary array that contained it.",
unknownAttributesAttribute.contains( 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( assertTrue(
"The " + (int)MsgFixture.UNKNOWN_ATTRIBUTES_3D_ATT +" attribute id "
+ "was not found after decoding a binary array that contained it.",
unknownAttributesAttribute.contains( 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(
assertEquals("The decoded attribute contained " MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST,
+ unknownAttributesAttribute.getAttributeCount() unknownAttributesAttribute.getAttributeCount(),
+ " attribute ids when there were only " "The decoded attribute contained "
+ (int)MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST + unknownAttributesAttribute.getAttributeCount()
+ " in the original binary array.", + " attribute ids when there were only "
MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST, + (int) MsgFixture.UNKNOWN_ATTRIBUTES_CNT_DEC_TST
unknownAttributesAttribute.getAttributeCount() + " in the original binary array."
); );
} }
/** /**
* Creates a new UnknownAttributesAttribute encodes it and assert equality * Creates a new UnknownAttributesAttribute encodes it and assert equality
* with binMessagesFixture.unknownAttsEncodeExpectedResult. * with binMessagesFixture.unknownAttsEncodeExpectedResult.
*/ */
@Test
public void testEncode() public void testEncode()
{ {
byte[] expectedReturn = binMessagesFixture.unknownAttsEncodeExpectedResult; byte[] expectedReturn = binMessagesFixture.unknownAttsEncodeExpectedResult;
@ -158,46 +159,36 @@ public class UnknownAttributesAttributeTest extends TestCase
unknownAttributesAttribute.addAttributeID( unknownAttributesAttribute.addAttributeID(
MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT); MsgFixture.UNKNOWN_ATTRIBUTES_2ND_ATT);
byte[] actualReturn = unknownAttributesAttribute.encode(); byte[] actualReturn = unknownAttributesAttribute.encode();
assertTrue("UnknownAttributesAttribute did not encode properly.", assertArrayEquals(actualReturn, expectedReturn);
Arrays.equals(actualReturn, expectedReturn));
} }
/** /**
* Tests the equals method against a null, a different and an identical * Tests the equals method against a null, a different and an identical
* object. * object.
*/ */
@Test
public void testEquals() public void testEquals()
{ {
UnknownAttributesAttribute target = new UnknownAttributesAttribute(); UnknownAttributesAttribute target = new UnknownAttributesAttribute();
boolean expectedReturn = false; assertNotEquals(unknownAttributesAttribute, null);
boolean actualReturn = unknownAttributesAttribute.equals(null);
assertEquals("Equals failed for a null object",
expectedReturn, actualReturn);
unknownAttributesAttribute.addAttributeID((char)25); unknownAttributesAttribute.addAttributeID((char)25);
target.addAttributeID((char)25); target.addAttributeID((char)25);
unknownAttributesAttribute.addAttributeID((char)26); unknownAttributesAttribute.addAttributeID((char)26);
actualReturn = unknownAttributesAttribute.equals(target); assertNotEquals(unknownAttributesAttribute, target);
assertEquals("Equals failed when comparing different objects.",
expectedReturn, actualReturn);
target.addAttributeID((char)26); target.addAttributeID((char)26);
expectedReturn = true; assertEquals(unknownAttributesAttribute, target);
actualReturn = unknownAttributesAttribute.equals(target);
assertEquals("Equals failed to recognize identical objects.",
expectedReturn, actualReturn);
} }
/** /**
* Tests that getAttribute() return the correct attribute id, preserving * Tests that getAttribute() return the correct attribute id, preserving
* entry order. * entry order.
*/ */
@Test
public void testGetAttribute() public void testGetAttribute()
{ {
char expectedId1 = 20; char expectedId1 = 20;
@ -212,14 +203,15 @@ public class UnknownAttributesAttributeTest extends TestCase
actualId1 = unknownAttributesAttribute.getAttribute(0); actualId1 = unknownAttributesAttribute.getAttribute(0);
actualId2 = unknownAttributesAttribute.getAttribute(1); actualId2 = unknownAttributesAttribute.getAttribute(1);
assertEquals("getAttribute() return value mismatch", expectedId1, actualId1); assertEquals(expectedId1, actualId1, "getAttribute() return value mismatch");
assertEquals("getAttribute() return value mismatch", expectedId2, actualId2); assertEquals(expectedId2, actualId2, "getAttribute() return value mismatch");
} }
/** /**
* Add some attributes and test whether their number is properly calculated. * Add some attributes and test whether their number is properly calculated.
* Tests duplicate id handling as well. * Tests duplicate id handling as well.
*/ */
@Test
public void testGetAttributeCount() public void testGetAttributeCount()
{ {
int expectedReturn = 5; int expectedReturn = 5;
@ -232,14 +224,15 @@ public class UnknownAttributesAttributeTest extends TestCase
unknownAttributesAttribute.addAttributeID((char)25);//duplicate values should be ignored unknownAttributesAttribute.addAttributeID((char)25);//duplicate values should be ignored
int actualReturn = unknownAttributesAttribute.getAttributeCount(); int actualReturn = unknownAttributesAttribute.getAttributeCount();
assertEquals("getAttributeCount did not return the expected value", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "getAttributeCount did not return the expected value");
} }
/** /**
* Same as testGetAttributeID, only attribute attributes are extracted * Same as testGetAttributeID, only attribute attributes are extracted
* through the getAttributes()'s iterator. * through the getAttributes()'s iterator.
*/ */
@Test
public void testGetAttributes() public void testGetAttributes()
{ {
char expectedId1 = 20; char expectedId1 = 20;
@ -256,10 +249,8 @@ public class UnknownAttributesAttributeTest extends TestCase
actualId1 = iterator.next(); actualId1 = iterator.next();
actualId2 = iterator.next(); actualId2 = iterator.next();
assertEquals("getAttributes() return value mismatch", expectedId1, actualId1); assertEquals(expectedId1, actualId1, "getAttributes() return value mismatch");
assertEquals("getAttributes() return value mismatch", expectedId2, actualId2); 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 * Test is first performed for an odd number of attributes and then again
* (after adding another attribute id). Both results should be the same. * (after adding another attribute id). Both results should be the same.
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = 8; char expectedReturn = 8;
@ -276,25 +268,23 @@ public class UnknownAttributesAttributeTest extends TestCase
unknownAttributesAttribute.addAttributeID((char)22); unknownAttributesAttribute.addAttributeID((char)22);
char actualReturn = unknownAttributesAttribute.getDataLength(); char actualReturn = unknownAttributesAttribute.getDataLength();
assertEquals("Incorrect testGetDataLength() return value", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "Incorrect testGetDataLength() return value");
unknownAttributesAttribute.addAttributeID((char)23); unknownAttributesAttribute.addAttributeID((char)23);
actualReturn = unknownAttributesAttribute.getDataLength(); actualReturn = unknownAttributesAttribute.getDataLength();
assertEquals("Incorrect testGetDataLength() return value", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "Incorrect testGetDataLength() return value");
} }
/** /**
* Tests whether getName returns a relevant name. * Tests whether getName returns a relevant name.
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "UNKNOWN-ATTRIBUTES"; assertEquals("UNKNOWN-ATTRIBUTES", unknownAttributesAttribute.getName());
String actualReturn = unknownAttributesAttribute.getName();
assertEquals("getName() return", expectedReturn, actualReturn);
} }
} }

View File

@ -17,19 +17,17 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* Tests the username attribute class. * Tests the username attribute class.
* *
* @author Emil Ivov * @author Emil Ivov
* @author Sebastien Vincent * @author Sebastien Vincent
*/ */
public class UsernameAttributeTest extends TestCase public class UsernameAttributeTest
{ {
private UsernameAttribute usernameAttribute = null; private UsernameAttribute usernameAttribute = null;
MsgFixture msgFixture = null; MsgFixture msgFixture = null;
@ -40,30 +38,27 @@ public class UsernameAttributeTest extends TestCase
0, (byte)usernameValue.length(), 0, (byte)usernameValue.length(),
'u', 's', 'e', 'r', 'n', 'a', 'm','e'}; 'u', 's', 'e', 'r', 'n', 'a', 'm','e'};
protected void setUp() throws Exception @BeforeEach
public void setUp() throws Exception
{ {
super.setUp();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
usernameAttribute = new UsernameAttribute(); usernameAttribute = new UsernameAttribute();
usernameAttribute.setUsername(usernameValue.getBytes()); usernameAttribute.setUsername(usernameValue.getBytes());
msgFixture.setUp();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
usernameAttribute = null; usernameAttribute = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Tests decoding of the username attribute. * Tests decoding of the username attribute.
* @throws StunException upon a failure * @throws StunException upon a failure
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
char offset = 0; char offset = 0;
@ -72,63 +67,62 @@ public class UsernameAttributeTest extends TestCase
decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length); decoded.decodeAttributeBody(usernameValue.getBytes(), offset, length);
//username value //username value
assertEquals( "decode failed", usernameAttribute, decoded); assertEquals(usernameAttribute, decoded);
} }
/** /**
* Tests the encode method * Tests the encode method
*/ */
@Test
public void testEncode() public void testEncode()
{ {
assertTrue("encode failed", assertArrayEquals(usernameAttribute.encode(), attributeBinValue);
Arrays.equals(usernameAttribute.encode(),
attributeBinValue));
} }
/** /**
* Test Equals * Test Equals
*/ */
@Test
public void testEquals() public void testEquals()
{ {
UsernameAttribute usernameAttribute2 = new UsernameAttribute(); UsernameAttribute usernameAttribute2 = new UsernameAttribute();
usernameAttribute2.setUsername(usernameValue.getBytes()); usernameAttribute2.setUsername(usernameValue.getBytes());
//test positive equals //test positive equals
assertEquals("testequals failed", usernameAttribute, usernameAttribute2); assertEquals(usernameAttribute, usernameAttribute2);
//test negative equals //test negative equals
usernameAttribute2 = new UsernameAttribute(); usernameAttribute2 = new UsernameAttribute();
usernameAttribute2.setUsername("some other username".getBytes()); usernameAttribute2.setUsername("some other username".getBytes());
//test positive equals //test positive equals
assertFalse("testequals failed", assertNotEquals(usernameAttribute2, usernameAttribute);
usernameAttribute.equals(usernameAttribute2));
//test null equals //test null equals
assertFalse("testequals failed", assertNotEquals(usernameAttribute, null);
usernameAttribute.equals(null));
} }
/** /**
* Tests extracting data length * Tests extracting data length
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = (char)usernameValue.length(); char expectedReturn = (char)usernameValue.length();
char actualReturn = usernameAttribute.getDataLength(); char actualReturn = usernameAttribute.getDataLength();
assertEquals("getDataLength - failed", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
/** /**
* Tests getting the name * Tests getting the name
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "USERNAME"; assertEquals("USERNAME", usernameAttribute.getName());
String actualReturn = usernameAttribute.getName();
assertEquals("getting name failed", expectedReturn, actualReturn);
} }
@Test
public void testSetGetUsername() public void testSetGetUsername()
{ {
byte[] expectedReturn = usernameValue.getBytes(); byte[] expectedReturn = usernameValue.getBytes();
@ -137,8 +131,7 @@ public class UsernameAttributeTest extends TestCase
att.setUsername(expectedReturn); att.setUsername(expectedReturn);
byte[] actualReturn = att.getUsername(); byte[] actualReturn = att.getUsername();
assertTrue("username setter or getter failed", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( expectedReturn, "username setter or getter failed");
actualReturn));
} }
} }

View File

@ -17,32 +17,30 @@
*/ */
package org.ice4j.attribute; package org.ice4j.attribute;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.jupiter.api.*;
/** /**
* @author Emil Ivov * @author Emil Ivov
*/ */
public class XorOnlyTest extends TestCase public class XorOnlyTest
{ {
private XorOnlyAttribute xorOnly = null; private XorOnlyAttribute xorOnly = null;
private MsgFixture msgFixture = null; private MsgFixture msgFixture = null;
protected void setUp() throws Exception @BeforeEach
public void setUp() throws Exception
{ {
super.setUp();
xorOnly = new XorOnlyAttribute(); xorOnly = new XorOnlyAttribute();
msgFixture = new MsgFixture(); msgFixture = new MsgFixture();
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
xorOnly = null; xorOnly = null;
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
@ -50,6 +48,7 @@ public class XorOnlyTest extends TestCase
* decode method doesn't do anything in the XorOnly att. * decode method doesn't do anything in the XorOnly att.
* @throws StunException if sth happens * @throws StunException if sth happens
*/ */
@Test
public void testDecodeAttributeBody() throws StunException public void testDecodeAttributeBody() throws StunException
{ {
byte[] attributeValue = new byte[]{}; byte[] attributeValue = new byte[]{};
@ -61,52 +60,52 @@ public class XorOnlyTest extends TestCase
/** /**
* Test encoding XorOnly attributes. * Test encoding XorOnly attributes.
*/ */
@Test
public void testEncode() public void testEncode()
{ {
byte[] expectedReturn = new byte[]{Attribute.XOR_ONLY>>8, byte[] expectedReturn = new byte[]{Attribute.XOR_ONLY>>8,
Attribute.XOR_ONLY&0x00FF, Attribute.XOR_ONLY&0x00FF,
0, 0}; 0, 0};
byte[] actualReturn = xorOnly.encode(); byte[] actualReturn = xorOnly.encode();
assertTrue("XorOnly failed to encode", assertArrayEquals(expectedReturn, actualReturn);
Arrays.equals( expectedReturn, actualReturn));
} }
/** /**
* Test positive and negative XorOnly.equals() returns * Test positive and negative XorOnly.equals() returns
* @throws Exception if decoding fails * @throws Exception if decoding fails
*/ */
@Test
public void testEquals() throws Exception public void testEquals() throws Exception
{ {
XorOnlyAttribute xor2 = new XorOnlyAttribute(); XorOnlyAttribute xor2 = new XorOnlyAttribute();
assertEquals("equals() failes for XorOnly", xorOnly, xor2); assertEquals(xorOnly, xor2);
MappedAddressAttribute maatt = new MappedAddressAttribute(); MappedAddressAttribute maatt = new MappedAddressAttribute();
maatt.decodeAttributeBody( msgFixture.mappedAddress, maatt.decodeAttributeBody( msgFixture.mappedAddress,
(char) 0, (char) 0,
(char) msgFixture.mappedAddress.length ); (char) msgFixture.mappedAddress.length );
assertNotEquals(maatt, xorOnly);
assertFalse("equals failed to see a difference", xorOnly.equals(maatt)); assertNotEquals(xorOnly, null);
assertFalse("equals failed for null", xorOnly.equals(null));
} }
/** /**
* Makes sure the data langth is 0 * Makes sure the data langth is 0
*/ */
@Test
public void testGetDataLength() public void testGetDataLength()
{ {
char expectedReturn = 0; char expectedReturn = 0;
char actualReturn = xorOnly.getDataLength(); 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?). * Verifies the name (do we really need this?).
*/ */
@Test
public void testGetName() public void testGetName()
{ {
String expectedReturn = "XOR-ONLY"; assertEquals("XOR-ONLY", xorOnly.getName());
String actualReturn = xorOnly.getName();
assertEquals("Is name correct", expectedReturn, actualReturn);
} }
} }

View File

@ -17,9 +17,9 @@
*/ */
package org.ice4j.ice; 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 public class NetworkUtilsTest
{ {

View File

@ -1,196 +1,198 @@
/* /*
* ice4j, the OpenSource Java Solution for NAT and Firewall Traversal. * ice4j, the OpenSource Java Solution for NAT and Firewall Traversal.
* *
* Copyright @ 2019 8x8, Inc * Copyright @ 2019 8x8, Inc
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.ice4j.ice; package org.ice4j.ice;
import org.ice4j.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.*;
import org.ice4j.*;
import java.io.*;
import java.util.*; import java.io.*;
import java.util.concurrent.*; import java.util.*;
import java.util.logging.*; 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. /**
* * RoleConflictResolutionTest set of tests which does end-to-end test
* @author Yura Yaroshevich * of ICE role conflict recovery.
*/ *
public class RoleConflictResolutionTest * @author Yura Yaroshevich
{ */
protected static final Logger logger public class RoleConflictResolutionTest
= Logger.getLogger(RoleConflictResolutionTest.class.getName()); {
protected static final Logger logger
@Test = Logger.getLogger(RoleConflictResolutionTest.class.getName());
public void testRecoveryFromBothControlledConflict()
throws Throwable @Test
{ public void testRecoveryFromBothControlledConflict()
testRecoveryFromRoleConflict(false); throws Throwable
} {
testRecoveryFromRoleConflict(false);
@Test }
public void testRecoveryFromBothControllingConflict()
throws Throwable @Test
{ public void testRecoveryFromBothControllingConflict()
testRecoveryFromRoleConflict(true); throws Throwable
} {
testRecoveryFromRoleConflict(true);
private static void testRecoveryFromRoleConflict(boolean bothControlling) }
throws Throwable
{ private static void testRecoveryFromRoleConflict(boolean bothControlling)
final Agent peer1 = createPeer("[peer-1]", bothControlling); throws Throwable
// Set explicit tie-breakers to avoid automatic conflict resolution {
peer1.setTieBreaker(1); final Agent peer1 = createPeer("[peer-1]", bothControlling);
// Set explicit tie-breakers to avoid automatic conflict resolution
final Agent peer2 = createPeer("[peer-2]", bothControlling); peer1.setTieBreaker(1);
peer1.setTieBreaker(2);
final Agent peer2 = createPeer("[peer-2]", bothControlling);
final CountDownLatch countDownLatch = new CountDownLatch(2); peer1.setTieBreaker(2);
for (Agent peer : Arrays.asList(peer1, peer2)) final CountDownLatch countDownLatch = new CountDownLatch(2);
{
peer.addStateChangeListener(evt -> for (Agent peer : Arrays.asList(peer1, peer2))
{ {
logger.info(peer.toString() + ": state changed to " peer.addStateChangeListener(evt ->
+ evt.toString()); {
if (peer.getState().isEstablished()) logger.info(peer.toString() + ": state changed to "
{ + evt.toString());
countDownLatch.countDown(); if (peer.getState().isEstablished())
} {
}); countDownLatch.countDown();
} }
});
exchangeCredentials(peer1, peer2); }
exchangeCandidates(peer1, peer2);
exchangeCredentials(peer1, peer2);
peer1.startConnectivityEstablishment(); exchangeCandidates(peer1, peer2);
peer2.startConnectivityEstablishment();
peer1.startConnectivityEstablishment();
boolean isConnected = countDownLatch.await(20, TimeUnit.SECONDS); peer2.startConnectivityEstablishment();
logSelectedPairs(peer1); boolean isConnected = countDownLatch.await(20, TimeUnit.SECONDS);
logSelectedPairs(peer2);
logSelectedPairs(peer1);
Assert.assertTrue("Expected connection established within time out", logSelectedPairs(peer2);
isConnected);
Assert.assertTrue("peer 1 connectivity", assertTrue(isConnected,
peer1.getState().isEstablished()); "Expected connection established within time out");
Assert.assertTrue("peer 2 connectivity", assertTrue(peer1.getState().isEstablished(),
peer2.getState().isEstablished()); "peer 1 connectivity");
assertTrue(peer2.getState().isEstablished(),
disposePeer(peer1); "peer 2 connectivity");
disposePeer(peer2);
} disposePeer(peer1);
disposePeer(peer2);
private static Agent createPeer(String label, boolean iceControlling) }
throws IOException
{ private static Agent createPeer(String label, boolean iceControlling)
final Agent agent = new Agent(label, null); throws IOException
agent.setControlling(iceControlling); {
IceMediaStream iceStream = agent.createMediaStream("media-stream"); final Agent agent = new Agent(label, null);
agent.setControlling(iceControlling);
agent.createComponent( IceMediaStream iceStream = agent.createMediaStream("media-stream");
iceStream,
Transport.UDP, agent.createComponent(
0x400, 0x400, 0xFFFF, iceStream,
KeepAliveStrategy.ALL_SUCCEEDED, Transport.UDP,
true); 0x400, 0x400, 0xFFFF,
KeepAliveStrategy.ALL_SUCCEEDED,
return agent; true);
}
return agent;
private static void disposePeer(Agent peer) }
{
peer.free(); private static void disposePeer(Agent peer)
} {
peer.free();
private static void logSelectedPairs(Agent peer) }
{
for (IceMediaStream stream : peer.getStreams()) private static void logSelectedPairs(Agent peer)
{ {
for (Component component : stream.getComponents()) for (IceMediaStream stream : peer.getStreams())
{ {
CandidatePair selectedPair = component.getSelectedPair(); for (Component component : stream.getComponents())
if (selectedPair != null) {
{ CandidatePair selectedPair = component.getSelectedPair();
logger.info( peer.toString() + ": selected pair for " + if (selectedPair != null)
"component " + component.getName() + " :" + {
selectedPair.toString()); 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()) private static void exchangeCredentials(Agent peer1, Agent peer2)
{ {
stream.setRemoteUfrag(peer1.getLocalUfrag()); for(IceMediaStream stream : peer2.getStreams())
stream.setRemotePassword(peer1.getLocalPassword()); {
} stream.setRemoteUfrag(peer1.getLocalUfrag());
stream.setRemotePassword(peer1.getLocalPassword());
for(IceMediaStream stream : peer1.getStreams()) }
{
stream.setRemoteUfrag(peer2.getLocalUfrag()); for(IceMediaStream stream : peer1.getStreams())
stream.setRemotePassword(peer2.getLocalPassword()); {
} stream.setRemoteUfrag(peer2.getLocalUfrag());
} stream.setRemotePassword(peer2.getLocalPassword());
}
private static void exchangeCandidates(Agent peer1, Agent peer2) }
{
for (String streamName : peer1.getStreamNames()) private static void exchangeCandidates(Agent peer1, Agent peer2)
{ {
IceMediaStream peer1Stream = peer1.getStream(streamName); for (String streamName : peer1.getStreamNames())
IceMediaStream peer2Stream = peer2.getStream(streamName); {
if (peer1Stream == null || peer2Stream == null) IceMediaStream peer1Stream = peer1.getStream(streamName);
{ IceMediaStream peer2Stream = peer2.getStream(streamName);
continue; if (peer1Stream == null || peer2Stream == null)
} {
continue;
for (Integer id : peer1Stream.getComponentIDs()) }
{
Component peer1Component = peer1Stream.getComponent(id); for (Integer id : peer1Stream.getComponentIDs())
Component peer2Component = peer2Stream.getComponent(id); {
if (peer1Component == null || peer2Component == null) Component peer1Component = peer1Stream.getComponent(id);
{ Component peer2Component = peer2Stream.getComponent(id);
continue; if (peer1Component == null || peer2Component == null)
} {
continue;
copyRemoteCandidates(peer1Component, peer2Component); }
copyRemoteCandidates(peer2Component, peer1Component);
} copyRemoteCandidates(peer1Component, peer2Component);
} copyRemoteCandidates(peer2Component, peer1Component);
} }
}
private static void copyRemoteCandidates(Component localComponent, }
Component remoteComponent)
{ private static void copyRemoteCandidates(Component localComponent,
for(LocalCandidate candidate : remoteComponent.getLocalCandidates()) Component remoteComponent)
{ {
localComponent.addRemoteCandidate( for(LocalCandidate candidate : remoteComponent.getLocalCandidates())
new RemoteCandidate( {
candidate.getTransportAddress(), localComponent.addRemoteCandidate(
localComponent, new RemoteCandidate(
candidate.getType(), candidate.getTransportAddress(),
candidate.getFoundation(), localComponent,
candidate.getPriority(), candidate.getType(),
null)); candidate.getFoundation(),
} candidate.getPriority(),
} null));
} }
}
}

View File

@ -17,10 +17,12 @@
*/ */
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.*; import org.ice4j.*;
import org.junit.*;
import java.net.*; import java.net.*;
import org.junit.jupiter.api.*;
/** /**
* Various tests that verify the functionality provided by {@link SinglePortUdpHarvester}. * Various tests that verify the functionality provided by {@link SinglePortUdpHarvester}.
@ -34,8 +36,8 @@ public class SinglePortUdpHarvesterTest
* *
* @see <a href="https://github.com/jitsi/ice4j/issues/139">https://github.com/jitsi/ice4j/issues/139</a> * @see <a href="https://github.com/jitsi/ice4j/issues/139">https://github.com/jitsi/ice4j/issues/139</a>
*/ */
@Test( expected = java.net.BindException.class ) @Test
public void testRebindWithoutClose() throws Exception public void testRebindWithoutCloseThrows() throws Exception
{ {
// Setup test fixture. // Setup test fixture.
final TransportAddress address = new TransportAddress( "127.0.0.1", 10000, Transport.UDP ); final TransportAddress address = new TransportAddress( "127.0.0.1", 10000, Transport.UDP );
@ -44,7 +46,7 @@ public class SinglePortUdpHarvesterTest
{ {
firstHarvester = new SinglePortUdpHarvester( address ); 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 // 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 // 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 try
{ {
secondHarvester = new SinglePortUdpHarvester( address ); 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 finally
{ {
// Tear down
firstHarvester.close(); firstHarvester.close();
if ( secondHarvester != null ) if (secondHarvester != null)
{ {
secondHarvester.close(); secondHarvester.close();
} }
@ -96,7 +101,7 @@ public class SinglePortUdpHarvesterTest
// Verify results. // Verify results.
catch ( BindException ex ) 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. // Tear down.

View File

@ -17,36 +17,15 @@
*/ */
package org.ice4j.message; package org.ice4j.message;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
import org.junit.jupiter.api.*;
public class MessageFactoryTest extends TestCase public class MessageFactoryTest
{ {
private MsgFixture msgFixture; @Test
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();
}
public void testCreateBindingErrorResponse() throws StunException public void testCreateBindingErrorResponse() throws StunException
{ {
char errorCode = 400; char errorCode = 400;
@ -60,10 +39,11 @@ public class MessageFactoryTest extends TestCase
Message actualReturn Message actualReturn
= MessageFactory.createBindingErrorResponse(errorCode); = MessageFactory.createBindingErrorResponse(errorCode);
assertEquals("return value", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
public void testCreateBindingErrorResponse1() throws StunException @Test
public void testCreateBindingErrorResponse1()
{ {
char errorCode = 400; char errorCode = 400;
String reasonPhrase = "Bad Request"; String reasonPhrase = "Bad Request";
@ -77,10 +57,10 @@ public class MessageFactoryTest extends TestCase
Message actualReturn = MessageFactory Message actualReturn = MessageFactory
.createBindingErrorResponse(errorCode, reasonPhrase); .createBindingErrorResponse(errorCode, reasonPhrase);
assertEquals("Failed to create an error code attribute.", assertEquals(expectedReturn, actualReturn);
expectedReturn, actualReturn);
} }
@Test
public void testCreateBindingErrorResponseUnknownAttributes() public void testCreateBindingErrorResponseUnknownAttributes()
throws StunException throws StunException
{ {
@ -91,17 +71,18 @@ public class MessageFactoryTest extends TestCase
Response expectedReturn = new Response(); Response expectedReturn = new Response();
expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE); expectedReturn.setMessageType(Message.BINDING_ERROR_RESPONSE);
Attribute errorCodeAtt = AttributeFactory ErrorCodeAttribute errorCodeAtt = AttributeFactory
.createErrorCodeAttribute(errorCode); .createErrorCodeAttribute(errorCode);
((ErrorCodeAttribute)errorCodeAtt).setReasonPhrase( errorCodeAtt.setReasonPhrase(
ErrorCodeAttribute.getDefaultReasonPhrase(errorCode)); ErrorCodeAttribute.getDefaultReasonPhrase(errorCode));
expectedReturn.putAttribute(errorCodeAtt); expectedReturn.putAttribute(errorCodeAtt);
UnknownAttributesAttribute unknownAtts = UnknownAttributesAttribute unknownAtts =
AttributeFactory.createUnknownAttributesAttribute(); AttributeFactory.createUnknownAttributesAttribute();
for (int i = 0; i < unknownAttributes.length; i++) { for (char unknownAttribute : unknownAttributes)
unknownAtts.addAttributeID(unknownAttributes[i]); {
unknownAtts.addAttributeID(unknownAttribute);
} }
expectedReturn.putAttribute(unknownAtts); expectedReturn.putAttribute(unknownAtts);
@ -109,9 +90,10 @@ public class MessageFactoryTest extends TestCase
Message actualReturn = MessageFactory Message actualReturn = MessageFactory
.createBindingErrorResponseUnknownAttributes(unknownAttributes); .createBindingErrorResponseUnknownAttributes(unknownAttributes);
//compare //compare
assertEquals("return value", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
@Test
public void testCreateBindingErrorResponseUnknownAttributes1() public void testCreateBindingErrorResponseUnknownAttributes1()
throws StunException throws StunException
{ {
@ -129,22 +111,22 @@ public class MessageFactoryTest extends TestCase
UnknownAttributesAttribute unknownAtts = UnknownAttributesAttribute unknownAtts =
AttributeFactory.createUnknownAttributesAttribute(); AttributeFactory.createUnknownAttributesAttribute();
for (int i = 0; i < unknownAttributes.length; i++) for (char unknownAttribute : unknownAttributes)
{ {
unknownAtts.addAttributeID(unknownAttributes[i]); unknownAtts.addAttributeID(unknownAttribute);
} }
expectedReturn.putAttribute(unknownAtts); expectedReturn.putAttribute(unknownAtts);
Message actualReturn = MessageFactory Message actualReturn = MessageFactory
.createBindingErrorResponseUnknownAttributes( .createBindingErrorResponseUnknownAttributes(
reasonPhrase, unknownAttributes); reasonPhrase, unknownAttributes);
assertEquals("return value", expectedReturn, actualReturn); assertEquals(expectedReturn, actualReturn);
} }
public void testCreateBindingRequest() throws StunException @Test
public void testCreateBindingRequest()
{ {
Request bindingRequest = new Request(); Request bindingRequest = new Request();
Request expectedReturn = bindingRequest;
bindingRequest.setMessageType(Message.BINDING_REQUEST); bindingRequest.setMessageType(Message.BINDING_REQUEST);
/* /*
Attribute changeRequest = AttributeFactory.createChangeRequestAttribute( Attribute changeRequest = AttributeFactory.createChangeRequestAttribute(
@ -152,9 +134,10 @@ public class MessageFactoryTest extends TestCase
bindingRequest.putAttribute(changeRequest); bindingRequest.putAttribute(changeRequest);
*/ */
Request actualReturn = MessageFactory.createBindingRequest(); Request actualReturn = MessageFactory.createBindingRequest();
assertEquals("return value", expectedReturn, actualReturn); assertEquals(bindingRequest, actualReturn);
} }
@Test
public void testCreateBindingResponse() public void testCreateBindingResponse()
throws Exception throws Exception
{ {
@ -183,7 +166,6 @@ public class MessageFactoryTest extends TestCase
bindingResponse.putAttribute(changedAddress); bindingResponse.putAttribute(changedAddress);
Message expectedReturn = bindingResponse;
Message actualReturn = MessageFactory.create3489BindingResponse( Message actualReturn = MessageFactory.create3489BindingResponse(
new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS, new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS,
MsgFixture.ADDRESS_ATTRIBUTE_PORT, MsgFixture.ADDRESS_ATTRIBUTE_PORT,
@ -194,6 +176,6 @@ public class MessageFactoryTest extends TestCase
new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3, new TransportAddress( MsgFixture.ADDRESS_ATTRIBUTE_ADDRESS_3,
MsgFixture.ADDRESS_ATTRIBUTE_PORT_3, MsgFixture.ADDRESS_ATTRIBUTE_PORT_3,
Transport.UDP)); Transport.UDP));
assertEquals("return value", expectedReturn, actualReturn); assertEquals(bindingResponse, actualReturn);
} }
} }

View File

@ -17,15 +17,14 @@
*/ */
package org.ice4j.message; package org.ice4j.message;
import java.util.*; import static org.junit.jupiter.api.Assertions.*;
import junit.framework.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.attribute.*; import org.ice4j.attribute.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
public class MessageTest extends TestCase public class MessageTest
{ {
private Message bindingRequest = null; private Message bindingRequest = null;
private Message bindingResponse = null; private Message bindingResponse = null;
@ -43,12 +42,12 @@ public class MessageTest extends TestCase
*/ */
private StunStack stunStack; 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 = new MsgFixture();
msgFixture.setUp();
stunStack = new StunStack(); stunStack = new StunStack();
@ -89,7 +88,8 @@ public class MessageTest extends TestCase
bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID); bindingResponse.setTransactionID(MsgFixture.TRANSACTION_ID);
} }
protected void tearDown() throws Exception @AfterEach
public void tearDown() throws Exception
{ {
bindingRequest = null; bindingRequest = null;
bindingResponse = null; bindingResponse = null;
@ -97,48 +97,38 @@ public class MessageTest extends TestCase
sourceAddress = null; sourceAddress = null;
changedAddress = null; changedAddress = null;
changeRequest = null; changeRequest = null;
changeRequest = null;
stunStack = null; stunStack = null;
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
/** /**
* Adds and gets an attribute and test that they are the same then adds a * 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. * 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(); Response message = new Response();
message.setMessageType(Message.BINDING_SUCCESS_RESPONSE); message.setMessageType(Message.BINDING_SUCCESS_RESPONSE);
message.putAttribute(mappedAddress); message.putAttribute(mappedAddress);
Attribute getResult = null; Attribute getResult;
getResult = message.getAttribute(mappedAddress.getAttributeType()); getResult = message.getAttribute(mappedAddress.getAttributeType());
assertEquals("Originally added attribute did not match the one retrned " assertEquals(mappedAddress, getResult,
+"by getAttribute()", "Originally added attribute did not match the returned");
mappedAddress,
getResult);
//do it again //do it again
message.putAttribute(sourceAddress); message.putAttribute(sourceAddress);
getResult = message.getAttribute(sourceAddress.getAttributeType()); getResult = message.getAttribute(sourceAddress.getAttributeType());
assertEquals(sourceAddress, getResult,
assertEquals("The second attribute could not be extracted.", "The second attribute could not be extracted.");
sourceAddress,
getResult);
} }
/** /**
@ -147,6 +137,7 @@ public class MessageTest extends TestCase
* *
* @throws StunException java.lang.Exception if we fail * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testEncode() public void testEncode()
throws StunException throws StunException
{ {
@ -154,16 +145,16 @@ public class MessageTest extends TestCase
byte[] expectedReturn = msgFixture.bindingRequest; byte[] expectedReturn = msgFixture.bindingRequest;
byte[] actualReturn = bindingRequest.encode(stunStack); byte[] actualReturn = bindingRequest.encode(stunStack);
assertTrue("A binding request was not properly encoded", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( expectedReturn, actualReturn ) ); "A binding request was not properly encoded");
//Binding Response //Binding Response
expectedReturn = msgFixture.bindingResponse; expectedReturn = msgFixture.bindingResponse;
actualReturn = bindingResponse.encode(stunStack); actualReturn = bindingResponse.encode(stunStack);
assertTrue("A binding response was not properly encoded", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals( 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 * @throws Exception java.lang.Exception if we fail
*/ */
@Test
public void testDecode() public void testDecode()
throws Exception throws Exception
{ {
@ -179,21 +171,21 @@ public class MessageTest extends TestCase
Message expectedReturn = bindingRequest; Message expectedReturn = bindingRequest;
Message actualReturn = Message.decode(msgFixture.bindingRequest, Message actualReturn = Message.decode(msgFixture.bindingRequest,
(char)0, 0,
(char)msgFixture.bindingRequest.length); msgFixture.bindingRequest.length);
assertEquals("A binding request was not properly decoded", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn ); "A binding request was not properly decoded");
//Binding Response //Binding Response
expectedReturn = bindingResponse; expectedReturn = bindingResponse;
actualReturn = Message.decode(msgFixture.bindingResponse, actualReturn = Message.decode(msgFixture.bindingResponse,
(char)0, 0,
(char)msgFixture.bindingResponse.length); msgFixture.bindingResponse.length);
assertEquals("A binding response was not properly decoded", assertEquals(expectedReturn, actualReturn,
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 * @throws StunException java.lang.Exception if we fail
*/ */
@Test
public void testEquals() public void testEquals()
throws StunException throws StunException
{ {
Object target = null; assertNotEquals(bindingRequest, null,
boolean expectedReturn = false; "Equals failed against a null target");
boolean actualReturn = bindingRequest.equals(target);
assertEquals("Equals failed against a null target",
expectedReturn, actualReturn);
actualReturn = bindingResponse.equals(target); assertNotEquals(bindingResponse, null,
assertEquals("Equals failed against a null target", "Equals failed against a null target");
expectedReturn, actualReturn);
//different //different
actualReturn = bindingRequest.equals(bindingResponse); assertNotEquals(bindingRequest, bindingResponse,
assertEquals("Equals failed against a different target", "Equals failed against a different target");
expectedReturn, actualReturn);
actualReturn = bindingResponse.equals(bindingRequest); assertNotEquals(bindingResponse, bindingRequest,
assertEquals("Equals failed against a different target", "Equals failed against a different target");
expectedReturn, actualReturn);
//same
expectedReturn = true;
//Create a binding request with the same attributes as //Create a binding request with the same attributes as
//this.bindingRequest //this.bindingRequest
Request binReqTarget = new Request(); Request binReqTarget = new Request();
binReqTarget.setMessageType(Message.BINDING_REQUEST); binReqTarget.setMessageType(Message.BINDING_REQUEST);
binReqTarget.putAttribute(changeRequest); binReqTarget.putAttribute(changeRequest);
actualReturn = bindingRequest.equals(binReqTarget); assertEquals(bindingRequest, binReqTarget,
assertEquals("Equals failed against an equal target", "Equals failed against an equal target");
expectedReturn, actualReturn);
//Create a binding response with the same attributes as //Create a binding response with the same attributes as
//this.bindingRequest //this.bindingRequest
@ -243,42 +226,42 @@ public class MessageTest extends TestCase
binResTarget.putAttribute(mappedAddress); binResTarget.putAttribute(mappedAddress);
binResTarget.putAttribute(sourceAddress); binResTarget.putAttribute(sourceAddress);
binResTarget.putAttribute(changedAddress); binResTarget.putAttribute(changedAddress);
actualReturn = bindingResponse.equals(binResTarget); assertEquals(bindingResponse, binResTarget,
assertEquals("Equals failed against a different target", "Equals failed against a different target");
expectedReturn, actualReturn);
} }
/** /**
* Tests whether attributes are properly counted * Tests whether attributes are properly counted
*/ */
@Test
public void testGetAttributeCount() public void testGetAttributeCount()
{ {
int expectedReturn = 1; int expectedReturn = 1;
int actualReturn = bindingRequest.getAttributeCount(); int actualReturn = bindingRequest.getAttributeCount();
assertEquals("getAttributeCount failed for a bindingRequest", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "getAttributeCount failed for a bindingRequest");
expectedReturn = 3; expectedReturn = 3;
actualReturn = bindingResponse.getAttributeCount(); actualReturn = bindingResponse.getAttributeCount();
assertEquals("getAttributeCount failed for a bindingRequest", assertEquals(expectedReturn, actualReturn,
expectedReturn, actualReturn); "getAttributeCount failed for a bindingRequest");
} }
/** /**
* Test whether attributes are properly removed. * Test whether attributes are properly removed.
*/ */
@Test
public void testRemoveAttribute() public void testRemoveAttribute()
{ {
bindingRequest.removeAttribute(changeRequest.getAttributeType()); bindingRequest.removeAttribute(changeRequest.getAttributeType());
assertNull("An attribute was still in the request after being removed", assertNull(bindingRequest.getAttribute(changeRequest.getAttributeType()),
bindingRequest.getAttribute(changeRequest.getAttributeType())); "An attribute was still in the request after being removed");
//test count //test count
int expectedReturn = 0; int expectedReturn = 0;
int actualReturn = bindingRequest.getAttributeCount(); int actualReturn = bindingRequest.getAttributeCount();
assertEquals( assertEquals(expectedReturn, actualReturn,
"Attribute count did not change after removing an attribute", "Attribute count did not change after removing an attribute");
expectedReturn, actualReturn);
} }
} }

View File

@ -17,32 +17,26 @@
*/ */
package org.ice4j.pseudotcp; 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 * This class enables multi thread tests where main thread waits in loop for
* for specified condition to be met, while others perform some operations. * specified condition to be met, while others perform some operations. For
* For example until the connection is established or closed. * example until the connection is established or closed. It also registers
* It also registers default uncaught exception handler to catch exceptions * default uncaught exception handler to catch exceptions from other threads.
* from other threads. * <p>
*
* Condition checks are passed as IWaitUntilDone interface. * Condition checks are passed as IWaitUntilDone interface.
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class MultiThreadSupportTest public class MultiThreadSupportTest implements Thread.UncaughtExceptionHandler
extends TestCase
implements Thread.UncaughtExceptionHandler
{ {
private volatile Throwable testError; private volatile Throwable testError;
private volatile Thread errorThread; private volatile Thread errorThread;
private final Object testLock = new Object();
private final Object testLock = new Object();
public MultiThreadSupportTest()
{
}
@Override @Override
public void uncaughtException(Thread t, Throwable e) public void uncaughtException(Thread t, Throwable e)
{ {
@ -53,27 +47,30 @@ public class MultiThreadSupportTest
testLock.notifyAll(); testLock.notifyAll();
} }
} }
private long assertWaitInterval = 100; private static final long ASSERT_WAIT_INTERVAL = 100;
protected interface WaitUntilDone protected interface WaitUntilDone
{ {
public boolean isDone(); boolean isDone();
} }
protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs) protected boolean assert_wait_until(WaitUntilDone wait, long timeoutMs)
{ {
try try
{ {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
while (!wait.isDone() && (System.currentTimeMillis() - start) < timeoutMs) while (!wait.isDone()
&& (System.currentTimeMillis() - start) < timeoutMs)
{ {
synchronized (testLock) synchronized (testLock)
{ {
testLock.wait(assertWaitInterval); testLock.wait(ASSERT_WAIT_INTERVAL);
if (testError != null) if (testError != null)
{ {
testError.printStackTrace(); 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; return false;
} }
} }
} }

View File

@ -17,16 +17,13 @@
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.logging.*; import java.util.logging.*;
import org.junit.jupiter.api.*;
/**
*
* @author Pawel Domas
*/
public class PseudoTcpStreamTest public class PseudoTcpStreamTest
extends MultiThreadSupportTest extends MultiThreadSupportTest
{ {
@ -36,14 +33,10 @@ public class PseudoTcpStreamTest
private static final Logger logger = Logger private static final Logger logger = Logger
.getLogger(PseudoTcpStreamTest.class.getName()); .getLogger(PseudoTcpStreamTest.class.getName());
public PseudoTcpStreamTest()
{
}
/** /**
* Test one-way transfer with @link(PseudoTcpStream) * Test one-way transfer with @link(PseudoTcpStream)
* @throws IOException
*/ */
@Test
public void testConnectTransferClose() public void testConnectTransferClose()
throws IOException throws IOException
{ {
@ -69,7 +62,7 @@ public class PseudoTcpStreamTest
public void run() public void run()
{ {
try try
{ {
server.setDebugName("L"); server.setDebugName("L");
server.bind(serverAddress); server.bind(serverAddress);
server.accept(5000); server.accept(5000);
@ -94,7 +87,7 @@ public class PseudoTcpStreamTest
} }
} }
}); });
final PseudoTcpSocket client = final PseudoTcpSocket client =
new PseudoTcpSocketFactory().createSocket(); new PseudoTcpSocketFactory().createSocket();
Thread clientThread = new Thread(new Runnable() Thread clientThread = new Thread(new Runnable()
@ -103,7 +96,7 @@ public class PseudoTcpStreamTest
public void run() public void run()
{ {
try try
{ {
client.setDebugName("R"); client.setDebugName("R");
client.connect(serverAddress, 5000); client.connect(serverAddress, 5000);
// write single array // write single array
@ -124,11 +117,10 @@ public class PseudoTcpStreamTest
partsSize[i] = sizeB / partCount; partsSize[i] = sizeB / partCount;
} }
int written = 0; int written = 0;
for (int i = 0; i < partsSize.length; i++) for (int j : partsSize)
{ {
client.getOutputStream().write(bufferB, written, client.getOutputStream().write(bufferB, written, j);
partsSize[i]); written += j;
written += partsSize[i];
} }
assertEquals(sizeB, written); assertEquals(sizeB, written);
client.getOutputStream().flush(); client.getOutputStream().flush();
@ -191,35 +183,24 @@ public class PseudoTcpStreamTest
/** /**
* Test the timeout on accept method * Test the timeout on accept method
*/ */
@Test
public void testAccept() public void testAccept()
{ {
try assertThrows(IOException.class, ()->
{ {
PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0); PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0);
server.accept(10); server.accept(10);
fail("Should throw timeout exception"); });
}
catch (IOException ex)
{
// success
}
} }
/** /**
* Interface used to pass timeout test function * Interface used to pass timeout test function
* @author Pawel Domas
*
*/ */
private interface TimeoutOperationTest private interface TimeoutOperationTest
{ {
void testTimeout(PseudoTcpSocketImpl socket) throws IOException; void testTimeout(PseudoTcpSocketImpl socket) throws IOException;
} }
/**
*
* @param testOperation
* @throws UnknownHostException
*/
private void doTestTimeout(final TimeoutOperationTest testOperation) private void doTestTimeout(final TimeoutOperationTest testOperation)
throws Exception throws Exception
{ {
@ -234,7 +215,7 @@ public class PseudoTcpStreamTest
client = new PseudoTcpSocketImpl(0); client = new PseudoTcpSocketImpl(0);
//Servers thread waiting for connection //Servers thread waiting for connection
new Thread(new Runnable() new Thread(new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
@ -255,7 +236,7 @@ public class PseudoTcpStreamTest
{ {
//success //success
try try
{ {
server.close(); server.close();
} }
catch (IOException exc) catch (IOException exc)
@ -268,7 +249,6 @@ public class PseudoTcpStreamTest
//Clients thread connects and closes socket //Clients thread connects and closes socket
new Thread(new Runnable() new Thread(new Runnable()
{ {
@Override @Override
public void run() public void run()
{ {
@ -281,13 +261,12 @@ public class PseudoTcpStreamTest
catch (Exception e) catch (Exception e)
{ {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
}).start(); }).start();
//Waits for server to close socket //Waits for server to close socket
boolean done = assert_wait_until(new WaitUntilDone() boolean done = assert_wait_until(new WaitUntilDone()
{ {
@Override @Override
public boolean isDone() public boolean isDone()
{ {
@ -299,69 +278,55 @@ public class PseudoTcpStreamTest
fail("Test timed out"); fail("Test timed out");
} }
} }
/** /**
* Tests timeout on read method * Tests timeout on read method
* @throws UnknownHostException
*/ */
@Test
public void testReadTimeout() throws Exception public void testReadTimeout() throws Exception
{ {
doTestTimeout(new TimeoutOperationTest() doTestTimeout(socket ->
{ {
socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300);
@Override socket.getInputStream().read(new byte[500]);
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
{
socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300);
socket.getInputStream().read(new byte[500]);
}
}); });
} }
/** /**
* Tests timeout on write method * Tests timeout on write method
* @throws UnknownHostException
*/ */
@Test
public void testWriteTimeout() throws Exception public void testWriteTimeout() throws Exception
{ {
doTestTimeout(new TimeoutOperationTest() doTestTimeout(socket ->
{ {
@Override //buffer that will exceed stack's buffer size
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2];
{ socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
//buffer that will exceed stack's buffer size socket.getOutputStream().write(bigBuffer);
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 * Tests timeout on flush method
* @throws UnknownHostException
*/ */
@Test
public void testFlushTimeout() throws Exception public void testFlushTimeout() throws Exception
{ {
doTestTimeout(new TimeoutOperationTest() doTestTimeout(socket ->
{ {
@Override //buffer that will exceed stack's buffer size
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException 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 socket.getOutputStream().write(buffer);
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();
} }
catch(IOException e)
{
throw new RuntimeException("Unexpected exception: "+e);
}
socket.getOutputStream().flush();
}); });
} }
} }

View File

@ -20,7 +20,10 @@ package org.ice4j.pseudotcp;
import java.io.*; import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.pseudotcp.util.*; import org.ice4j.pseudotcp.util.*;
import org.junit.jupiter.api.*;
/** /**
* This class implements test for two way transfers * This class implements test for two way transfers
@ -51,10 +54,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
*/ */
private int iterationsRemaining; private int iterationsRemaining;
public PseudoTcpTestPingPong()
{
}
public void setBytesPerSend(int bytes_per_send) public void setBytesPerSend(int bytes_per_send)
{ {
this.bytesPerSend = bytes_per_send; this.bytesPerSend = bytes_per_send;
@ -71,11 +70,8 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Performs ping-pong test for <tt>iterations</tt> with packets of * Performs ping-pong test for <tt>iterations</tt> with packets of
* <tt>size</tt> bytes * <tt>size</tt> bytes
*
* @param size
* @param iterations
*/ */
public void doTestPingPong(int size, int iterations) private void doTestPingPong(int size, int iterations)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start; long start;
@ -113,13 +109,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Catches onTcpReadable event for receiver * Catches onTcpReadable event for receiver
*
* @param tcp
*/ */
@Override @Override
public void onTcpReadable(PseudoTCPBase tcp) public void onTcpReadable(PseudoTCPBase tcp)
{ {
assertEquals("Unexpected onTcpReadable", receiver, tcp); assertEquals(receiver, tcp, "Unexpected onTcpReadable");
try try
{ {
// Stream bytes to the recv stream as they arrive. // Stream bytes to the recv stream as they arrive.
@ -163,8 +157,6 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Catches the ontcpWriteable event for sender * Catches the ontcpWriteable event for sender
*
* @param tcp
*/ */
@Override @Override
public void onTcpWriteable(PseudoTCPBase tcp) public void onTcpWriteable(PseudoTCPBase tcp)
@ -189,13 +181,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Reads the data in loop until is something available * Reads the data in loop until is something available
*
* @throws IOException
*/ */
private void readData() throws IOException private void readData() throws IOException
{ {
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
int rcvd = 0; int rcvd;
do do
{ {
rcvd = receiver.recv(block, block.length); rcvd = receiver.recv(block, block.length);
@ -214,13 +204,11 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
/** /**
* Writes all data to the receiver * Writes all data to the receiver
*
* @throws IOException
*/ */
private void writeData() throws IOException private void writeData() throws IOException
{ {
int tosend; int tosend;
int sent = 0; int sent;
byte[] block = new byte[kBlockSize]; byte[] block = new byte[kBlockSize];
do do
{ {
@ -250,7 +238,7 @@ public class PseudoTcpTestPingPong extends PseudoTcpTestBase
while (sent > 0); while (sent > 0);
} }
/** /*
* *
* Ping-pong (request/response) tests * 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 sending <= 1x MTU of data in each ping/pong. Should take <10ms.
*/ */
@Test
public void testPingPong1xMtu() public void testPingPong1xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 1xMTU"); //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 sending 2x-3x MTU of data in each ping/pong. Should take <10ms.
*/ */
@Test
public void testPingPong3xMtu() public void testPingPong3xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 3xMTU"); //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 * Test sending 1x-2x MTU of data in each ping/pong. Should take ~1s, due to
* interaction between Nagling and Delayed ACK. * interaction between Nagling and Delayed ACK.
*/ */
@Test
public void testPingPong2xMtu() public void testPingPong2xMtu()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU"); //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. * Test sending 1x-2x MTU of data in each ping/pong with Delayed ACK off.
* Should take <10ms. * Should take <10ms.
*/ */
@Test
public void testPingPong2xMtuWithAckDelayOff() public void testPingPong2xMtuWithAckDelayOff()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU ack delay off"); //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 * Test sending 1x-2x MTU of data in each ping/pong with Nagling off. Should
* take <10ms. * take <10ms.
*/ */
@Test
public void testPingPong2xMtuWithNaglingOff() public void testPingPong2xMtuWithNaglingOff()
{ {
//logger.log(Level.INFO, "Test ping - pong 2xMTU nagling off"); //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 * Test sending a ping as pair of short (non-full) segments. Should take
* ~1s, due to Delayed ACK interaction with Nagling. * ~1s, due to Delayed ACK interaction with Nagling.
*/ */
@Test
public void testPingPongShortSegments() public void testPingPongShortSegments()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments"); //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 * Test sending ping as a pair of short (non-full) segments, with Nagling
* off. Should take <10ms. * off. Should take <10ms.
*/ */
@Test
public void testPingPongShortSegmentsWithNaglingOff() public void testPingPongShortSegmentsWithNaglingOff()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //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 * Test sending <= 1x MTU of data ping/pong, in two segments, no Delayed
* ACK. Should take ~1s. * ACK. Should take ~1s.
*/ */
@Test
public void testPingPongShortSegmentsWithAckDelayOff() public void testPingPongShortSegmentsWithAckDelayOff()
{ {
//logger.log(Level.INFO, "Test ping - pong short segments nagling off"); //logger.log(Level.INFO, "Test ping - pong short segments nagling off");

View File

@ -21,7 +21,10 @@ import java.io.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.pseudotcp.util.*; 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 * 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; private int testDataSize;
public void doTestTransfer(int size) private void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
testDataSize = size; testDataSize = size;
@ -94,15 +97,14 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
scheduleWriteAction(0); scheduleWriteAction(0);
long transferTout = maxTransferTime(dummy.length, kMinTransferRate); long transferTout = maxTransferTime(dummy.length, kMinTransferRate);
boolean transfferInTime = assert_Disconnected_wait(transferTout); boolean transferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.now() - start; elapsed = PseudoTCPBase.now() - start;
stopClocks(); stopClocks();
int received = recv_stream.getBuffered(); int received = recv_stream.getBuffered();
assertEquals("Transfer timeout, transferred: " + received assertTrue(transferInTime, "Transfer timeout, transferred: " + received
+ " required: " + dummy.length + " required: " + dummy.length
+ " elapsed: " + " elapsed: "
+ elapsed + " limit: " + transferTout, + elapsed + " limit: " + transferTout);
true, transfferInTime);
assert 2 == send_position.size(); assert 2 == send_position.size();
assert 2 == recv_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 * @return count bytes shadowed by scale actor
*/ */
static int getShadowedBytes(int scaleFactor) static int getShadowedBytes(int scaleFactor)
@ -151,8 +152,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Reads all data available at the buffer * Reads all data available at the buffer
*
* @throws IOException
*/ */
void readUntilIOPending() throws IOException void readUntilIOPending() throws IOException
{ {
@ -186,8 +185,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Schedules write operation with <tt>delay</tt> given in ms * Schedules write operation with <tt>delay</tt> given in ms
*
* @param delay
*/ */
void scheduleWriteAction(long delay) void scheduleWriteAction(long delay)
{ {
@ -212,8 +209,6 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Writes the data * Writes the data
*
* @throws IOException
*/ */
void writeData() throws IOException void writeData() throws IOException
{ {
@ -336,6 +331,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
return getRemoteTcp().getM_rwnd_scale(); return getRemoteTcp().getM_rwnd_scale();
} }
@Test
public void testGetShadowedBytes() public void testGetShadowedBytes()
{ {
assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0); assert (PseudoTcpTestRecvWindow.getShadowedBytes(0) == 0);
@ -350,6 +346,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Test that receive window expands and contract correctly. * Test that receive window expands and contract correctly.
*/ */
@Test
public void testReceiveWindow() public void testReceiveWindow()
{ {
//logger.log(Level.INFO, "Test receive window"); //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 setting send window size to a very small value.
*/ */
@Test
public void testSetVerySmallSendWindowSize() public void testSetVerySmallSendWindowSize()
{ {
//TODO: finish test //TODO: finish test
@ -381,6 +379,7 @@ public class PseudoTcpTestRecvWindow extends PseudoTcpTestBase
/** /**
* Test setting receive window size to a value other than default. * Test setting receive window size to a value other than default.
*/ */
@Test
public void testSetReceiveWindowSize() public void testSetReceiveWindowSize()
{ {
//logger.log(Level.INFO, "Test set receive window size"); //logger.log(Level.INFO, "Test set receive window size");

View File

@ -17,10 +17,11 @@
*/ */
package org.ice4j.pseudotcp; package org.ice4j.pseudotcp;
import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.*;
import java.io.*; import java.io.*;
import java.util.logging.*; import java.util.logging.*;
import org.junit.jupiter.api.*;
/** /**
* Implements one way transfer test * Implements one way transfer test
@ -35,10 +36,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
private static final Logger logger = private static final Logger logger =
Logger.getLogger(PseudoTCPBase.class.getName()); Logger.getLogger(PseudoTCPBase.class.getName());
public PseudoTcpTestTransfer()
{
super();
}
/** /**
* The send data * The send data
*/ */
@ -58,12 +55,10 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Transfers the data of <tt>size</tt> bytes * Transfers the data of <tt>size</tt> bytes
*
* @param size
*/ */
public void doTestTransfer(int size) private void doTestTransfer(int size)
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
long start, elapsed; long start, elapsed;
int received; int received;
// Create some dummy data to send // Create some dummy data to send
@ -78,7 +73,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
try try
{ {
connect(); connect();
//assertEquals(0, Connect());
} }
catch (IOException ex) catch (IOException ex)
{ {
@ -89,15 +83,14 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
// Sending will start from OnTcpWriteable and complete when all data has // Sending will start from OnTcpWriteable and complete when all data has
// been received. // been received.
long transferTout = maxTransferTime(sendData.length, kMinTransferRate); long transferTout = maxTransferTime(sendData.length, kMinTransferRate);
boolean transfferInTime = assert_Disconnected_wait(transferTout); boolean transferInTime = assert_Disconnected_wait(transferTout);
elapsed = PseudoTCPBase.now() - start; elapsed = PseudoTCPBase.now() - start;
stopClocks(); stopClocks();
received = recvStream.size(); received = recvStream.size();
assertEquals("Transfer timeout, transferred: " + received assertTrue(transferInTime,"Transfer timeout, transferred: " + received
+ " required: " + sendData.length + " required: " + sendData.length
+ " elapsed: " + " elapsed: "
+ elapsed + " limit: " + transferTout, + elapsed + " limit: " + transferTout);
true, transfferInTime);
// Ensure we closed down OK and we got the right data. // Ensure we closed down OK and we got the right data.
assertEquals(size, received); assertEquals(size, received);
@ -112,8 +105,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
/** /**
* Reads all data available at remote peer's buffer * Reads all data available at remote peer's buffer
*
* @throws IOException
*/ */
void readData() throws IOException void readData() throws IOException
{ {
@ -135,7 +126,6 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
* Writes the data until there's space available * Writes the data until there's space available
* *
* @return true if there's no more data left to write * @return true if there's no more data left to write
* @throws IOException
*/ */
boolean writeData() 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 * Catches TCP readable event for remote peer and reads the data. When total
* read count equals send data size the test is finished. * read count equals send data size the test is finished.
*
* @param tcp
*/ */
@Override @Override
public void onTcpReadable(PseudoTCPBase tcp) 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 * Catches on TCP writeable event for local peer. Writes all data and closes
* the stream * the stream
*
* @param tcp
*/ */
@Override @Override
public void onTcpWriteable(PseudoTCPBase tcp) 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 * Basic end-to-end data transfer tests Test the normal case of sending data
* from one side to the other. * from one side to the other.
*/ */
@Test
public void testSend() public void testSend()
{ {
//logger.log(Level.INFO, "Test send"); //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 * Test sending data with a 50 ms RTT. Transmission should take longer due
* to a slower ramp-up in send rate. * to a slower ramp-up in send rate.
*/ */
@Test
public void testSendWithDelay() public void testSendWithDelay()
{ {
//logger.log(Level.INFO, "Test send with delay"); //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 * Test sending data with packet loss. Transmission should take much longer
* due to send back-off when loss occurs. * due to send back-off when loss occurs.
*/ */
@Test
public void testSendWithLoss() public void testSendWithLoss()
{ {
//logger.log(Level.INFO, "Test send with loss"); //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 * should take much longer due to send back-off and slower detection of
* loss. * loss.
*/ */
@Test
public void testSendWithDelayAndLoss() public void testSendWithDelayAndLoss()
{ {
//logger.log(Level.INFO, "Test send with delay and loss"); //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 * Test sending data with 10% packet loss and Nagling disabled. Transmission
* should take about the same time as with Nagling enabled. * should take about the same time as with Nagling enabled.
*/ */
@Test
public void testSendWithLossAndOptNaglingOff() public void testSendWithLossAndOptNaglingOff()
{ {
//logger.log(Level.INFO, "Test send with loss and OptNagling off"); //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. * Test sending data with 10% packet loss and Delayed ACK disabled.
* Transmission should be slightly faster than with it enabled. * Transmission should be slightly faster than with it enabled.
*/ */
@Test
public void testSendWithLossAndOptAckDelayOff() public void testSendWithLossAndOptAckDelayOff()
{ {
//logger.log(Level.INFO, "Test send with loss and OptAckDelay off"); //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 sending data with 50ms delay and Nagling disabled.
*/ */
@Test
public void testSendWithDelayAndOptNaglingOff() public void testSendWithDelayAndOptNaglingOff()
{ {
//logger.log(Level.INFO, "Test send with delay and OptNagling off"); //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 sending data with 50ms delay and Delayed ACK disabled.
*/ */
@Test
public void testSendWithDelayAndOptAckDelayOff() public void testSendWithDelayAndOptAckDelayOff()
{ {
//logger.log(Level.INFO, "Test send with delay and OptAckDelay off"); //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 a large receive buffer with a sender that doesn't support scaling.
*/ */
@Test
public void testSendRemoteNoWindowScale() public void testSendRemoteNoWindowScale()
{ {
//logger.log(Level.INFO, "Test send - remote no window scale"); //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 * Test a large sender-side receive buffer with a receiver that doesn't
* support scaling. * support scaling.
*/ */
@Test
public void testSendLocalNoWindowScale() public void testSendLocalNoWindowScale()
{ {
//logger.log(Level.INFO, "Test send - local no window scale"); //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 when both sides use window scaling.
*/ */
@Test
public void testSendBothUseWindowScale() public void testSendBothUseWindowScale()
{ {
//logger.log(Level.INFO, "Test send - both use window scale"); //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 using a large window scale value.
*/ */
@Test
public void testSendLargeInFlight() public void testSendLargeInFlight()
{ {
//logger.log(Level.INFO, "Test send large in flight"); //logger.log(Level.INFO, "Test send large in flight");
@ -414,6 +412,7 @@ public class PseudoTcpTestTransfer extends PseudoTcpTestBase
test.doTestTransfer(1000000); test.doTestTransfer(1000000);
} }
@Test
public void testSendBothUseLargeWindowScale() public void testSendBothUseLargeWindowScale()
{ {
//logger.log(Level.INFO, "Test send both use large window scale"); //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 using a small receive buffer.
*/ */
@Test
public void testSendSmallReceiveBuffer() public void testSendSmallReceiveBuffer()
{ {
//logger.log(Level.INFO, "Test send small receive buffer"); //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 using a very small receive buffer.
*/ */
@Test
public void testSendVerySmallReceiveBuffer() public void testSendVerySmallReceiveBuffer()
{ {
//logger.log(Level.INFO, "Test send very small receive buffer"); //logger.log(Level.INFO, "Test send very small receive buffer");

View File

@ -17,19 +17,18 @@
*/ */
package org.ice4j.pseudotcp.util; package org.ice4j.pseudotcp.util;
import static org.junit.Assert.*;
import java.nio.*; import java.nio.*;
import java.util.*; import java.util.*;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.*;
/** /**
* *
* @author Pawel Domas * @author Pawel Domas
*/ */
public class ByteFifoBufferTest public class ByteFifoBufferTest
extends TestCase
{ {
public ByteFifoBufferTest() public ByteFifoBufferTest()
{ {
@ -38,6 +37,7 @@ public class ByteFifoBufferTest
/** /**
* Test of Length method, of class ByteFifoBuffer. * Test of Length method, of class ByteFifoBuffer.
*/ */
@Test
public void testLength() public void testLength()
{ {
int expResult = 1000; int expResult = 1000;
@ -52,6 +52,7 @@ public class ByteFifoBufferTest
/** /**
* Test of Read method, of class ByteFifoBuffer. * Test of Read method, of class ByteFifoBuffer.
*/ */
@Test
public void testRead() public void testRead()
{ {
int count = 1024; int count = 1024;
@ -60,9 +61,8 @@ public class ByteFifoBufferTest
instance.write(wData, count); instance.write(wData, count);
byte[] readBuff = new byte[count]; byte[] readBuff = new byte[count];
int expResult = count;
int result = instance.read(readBuff, count); int result = instance.read(readBuff, count);
assertEquals(expResult, result); assertEquals(count, result);
assertArrayEquals(wData, readBuff); assertArrayEquals(wData, readBuff);
} }
@ -70,6 +70,7 @@ public class ByteFifoBufferTest
/** /**
* Tests reading with an offset for destination buffer * Tests reading with an offset for destination buffer
*/ */
@Test
public void testReadWithOffset() public void testReadWithOffset()
{ {
int count = 1024; int count = 1024;
@ -93,7 +94,6 @@ public class ByteFifoBufferTest
* return some random array * return some random array
* *
* @param count array size * @param count array size
* @return
*/ */
private byte[] getWData(int count) private byte[] getWData(int count)
{ {
@ -106,6 +106,7 @@ public class ByteFifoBufferTest
/** /**
* Test of GetWriteRemaining method, of class ByteFifoBuffer. * Test of GetWriteRemaining method, of class ByteFifoBuffer.
*/ */
@Test
public void testGetWriteRemaining() public void testGetWriteRemaining()
{ {
int len = 100; int len = 100;
@ -126,6 +127,7 @@ public class ByteFifoBufferTest
/** /**
* Test of GetBuffered method, of class ByteFifoBuffer. * Test of GetBuffered method, of class ByteFifoBuffer.
*/ */
@Test
public void testGetBuffered() public void testGetBuffered()
{ {
int len = 1000; int len = 1000;
@ -148,14 +150,14 @@ public class ByteFifoBufferTest
/** /**
* Test of Write method, of class ByteFifoBuffer. * Test of Write method, of class ByteFifoBuffer.
*/ */
@Test
public void testWrite() public void testWrite()
{ {
int len = 2048; int len = 2048;
byte[] data = getWData(len); byte[] data = getWData(len);
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len;
int result = instance.write(data, len); int result = instance.write(data, len);
assertEquals(expResult, result); assertEquals(len, result);
byte[] read = new byte[len]; byte[] read = new byte[len];
int readCount = instance.read(read, len); int readCount = instance.read(read, len);
@ -163,6 +165,7 @@ public class ByteFifoBufferTest
assertArrayEquals(data, read); assertArrayEquals(data, read);
} }
@Test
public void testWriteWithOffset() public void testWriteWithOffset()
{ {
int len = 2048; int len = 2048;
@ -183,6 +186,7 @@ public class ByteFifoBufferTest
/** /**
* Test of ConsumeWriteBuffer method, of class ByteFifoBuffer. * Test of ConsumeWriteBuffer method, of class ByteFifoBuffer.
*/ */
@Test
public void testConsumeWriteBuffer() public void testConsumeWriteBuffer()
{ {
int len = 100; int len = 100;
@ -208,6 +212,7 @@ public class ByteFifoBufferTest
/** /**
* Test of SetCapacity method, of class ByteFifoBuffer. * Test of SetCapacity method, of class ByteFifoBuffer.
*/ */
@Test
public void testSetCapacity() public void testSetCapacity()
{ {
int old_size = 100; int old_size = 100;
@ -229,6 +234,7 @@ public class ByteFifoBufferTest
/** /**
* Test of ConsumeReadData method, of class ByteFifoBuffer. * Test of ConsumeReadData method, of class ByteFifoBuffer.
*/ */
@Test
public void testConsumeReadData() public void testConsumeReadData()
{ {
int lCount = 100; int lCount = 100;
@ -250,6 +256,7 @@ public class ByteFifoBufferTest
/** /**
* Test of ReadOffset method, of class ByteFifoBuffer. * Test of ReadOffset method, of class ByteFifoBuffer.
*/ */
@Test
public void testReadOffset() public void testReadOffset()
{ {
int dst_buff_offset = 0; int dst_buff_offset = 0;
@ -258,11 +265,10 @@ public class ByteFifoBufferTest
byte[] dst_buff = new byte[len]; byte[] dst_buff = new byte[len];
int offset = 0; int offset = 0;
ByteFifoBuffer instance = new ByteFifoBuffer(len); ByteFifoBuffer instance = new ByteFifoBuffer(len);
int expResult = len;
instance.write(src_buff, len); instance.write(src_buff, len);
int result = int result =
instance.readOffset(dst_buff, dst_buff_offset, len, offset); instance.readOffset(dst_buff, dst_buff_offset, len, offset);
assertEquals(expResult, result); assertEquals(len, result);
assertArrayEquals(dst_buff, src_buff); assertArrayEquals(dst_buff, src_buff);
} }
@ -270,6 +276,7 @@ public class ByteFifoBufferTest
/** /**
* Test of WriteOffset method, of class ByteFifoBuffer. * Test of WriteOffset method, of class ByteFifoBuffer.
*/ */
@Test
public void testWriteOffset() public void testWriteOffset()
{ {
int len = 200; int len = 200;
@ -301,6 +308,7 @@ public class ByteFifoBufferTest
} }
@Test
public void testWriteReadWriteRead() public void testWriteReadWriteRead()
{ {
int len = 2000; int len = 2000;
@ -330,6 +338,7 @@ public class ByteFifoBufferTest
while ((read != wrData.length) || (written != wrData.length)); while ((read != wrData.length) || (written != wrData.length));
} }
@Test
public void testSomeMultiTest() public void testSomeMultiTest()
{ {
int Alen = 16; int Alen = 16;

View File

@ -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());
}
}

View File

@ -18,21 +18,21 @@
package org.ice4j.stack; package org.ice4j.stack;
import java.net.*; import java.net.*;
import java.util.*;
import java.util.logging.*; import java.util.logging.*;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.socket.*; 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. * All unit stack tests should be provided later. I just don't have the time now.
* *
* @author Emil Ivov * @author Emil Ivov
*/ */
public class ShallowStackTest extends TestCase public class ShallowStackTest
{ {
/** /**
* The <tt>Logger</tt> used by the <tt>ShallowStackTest<tt> class and its * The <tt>Logger</tt> used by the <tt>ShallowStackTest<tt> class and its
@ -56,44 +56,34 @@ public class ShallowStackTest extends TestCase
private DatagramSocket dummyServerSocket = null; 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. * Initializes whatever sockets we'll be using in our tests.
* *
* @throws Exception if something goes wrong with socket initialization. * @throws Exception if something goes wrong with socket initialization.
*/ */
protected void setUp() @BeforeEach
public void setUp()
throws Exception throws Exception
{ {
super.setUp(); System.clearProperty(StackProperties.ALWAYS_SIGN);
System.clearProperty(StackProperties.SOFTWARE);
msgFixture = new MsgFixture(); 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 //init the stack
stunStack = new StunStack(); stunStack = new StunStack();
//access point //access point
localSock = new IceUdpSocketWrapper( 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); stunStack.addSocket(localSock);
//init the dummy server //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. * @throws Exception if closing the sockets fails.
*/ */
protected void tearDown() @AfterEach
public void tearDown()
throws Exception throws Exception
{ {
stunStack.removeSocket(localAddress); stunStack.removeSocket(localAddress);
stunStack.shutDown();
localSock.close(); localSock.close();
dummyServerSocket.close(); dummyServerSocket.close();
msgFixture.tearDown();
msgFixture = null; msgFixture = null;
super.tearDown();
} }
@ -123,6 +113,7 @@ public class ShallowStackTest extends TestCase
* *
* @throws java.lang.Exception if we fail * @throws java.lang.Exception if we fail
*/ */
@Test
public void testSendRequest() public void testSendRequest()
throws Exception throws Exception
{ {
@ -140,17 +131,15 @@ public class ShallowStackTest extends TestCase
DatagramPacket receivedPacket = dgramCollector.collectPacket(); DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not properly send a Binding Request", assertTrue((receivedPacket.getLength() > 0),
(receivedPacket.getLength() > 0)); "The stack did not properly send a Binding Request");
Request receivedRequest = Request receivedRequest =
(Request)Request.decode(receivedPacket.getData(), (Request)Request.decode(receivedPacket.getData(),
(char)0, (char)0,
(char)receivedPacket.getLength()); (char)receivedPacket.getLength());
assertEquals("The received request did not match the " assertEquals(bindingRequest, receivedRequest,
+"one that was sent.", "The received request did not match the one that was sent.");
bindingRequest, //expected
receivedRequest); // actual
//wait for retransmissions //wait for retransmissions
@ -160,16 +149,15 @@ public class ShallowStackTest extends TestCase
receivedPacket = dgramCollector.collectPacket(); receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not retransmit a Binding Request", assertTrue((receivedPacket.getLength() > 0),
(receivedPacket.getLength() > 0)); "The stack did not retransmit a Binding Request");
receivedRequest = (Request)Request.decode( receivedRequest = (Request)Request.decode(
receivedPacket.getData(), receivedPacket.getData(),
(char)0, 0,
(char)receivedPacket.getLength()); receivedPacket.getLength());
assertEquals("The retransmitted request did not match the original.", assertEquals(bindingRequest, receivedRequest,
bindingRequest, //expected "The retransmitted request did not match the original.");
receivedRequest); // actual
} }
/** /**
@ -178,6 +166,7 @@ public class ShallowStackTest extends TestCase
* *
* @throws java.lang.Exception if we fail * @throws java.lang.Exception if we fail
*/ */
@Test
public void testReceiveRequest() public void testReceiveRequest()
throws Exception throws Exception
{ {
@ -194,12 +183,12 @@ public class ShallowStackTest extends TestCase
Request collectedRequest = requestCollector.collectedRequest; Request collectedRequest = requestCollector.collectedRequest;
assertNotNull("No request has been received", collectedRequest); assertNotNull(collectedRequest, "No request has been received");
byte expectedReturn[] = msgFixture.bindingRequest2; byte[] expectedReturn = msgFixture.bindingRequest2;
byte actualReturn[] = collectedRequest.encode(stunStack); byte[] actualReturn = collectedRequest.encode(stunStack);
assertTrue("Received request was not the same as the one that was sent", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals(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 * @throws java.lang.Exception if we fail
*/ */
@Test
public void testSendResponse() public void testSendResponse()
throws Exception throws Exception
{ {
@ -227,10 +217,10 @@ public class ShallowStackTest extends TestCase
Request collectedRequest = requestCollector.collectedRequest; Request collectedRequest = requestCollector.collectedRequest;
byte expectedReturn[] = msgFixture.bindingRequest; byte[] expectedReturn = msgFixture.bindingRequest;
byte actualReturn[] = collectedRequest.encode(stunStack); byte[] actualReturn = collectedRequest.encode(stunStack);
assertTrue("Received request was not the same as the one that was sent", assertArrayEquals(expectedReturn, actualReturn,
Arrays.equals(expectedReturn, actualReturn)); "Received request was not the same as the one that was sent");
//---------- create the response --------------------------------------- //---------- create the response ---------------------------------------
Response bindingResponse = MessageFactory.create3489BindingResponse( Response bindingResponse = MessageFactory.create3489BindingResponse(
@ -254,17 +244,15 @@ public class ShallowStackTest extends TestCase
DatagramPacket receivedPacket = dgramCollector.collectPacket(); DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not properly send a Binding Request", assertTrue((receivedPacket.getLength() > 0),
(receivedPacket.getLength() > 0)); "The stack did not properly send a Binding Request");
Response receivedResponse = Response receivedResponse =
(Response) Response.decode(receivedPacket.getData(), (Response) Response.decode(receivedPacket.getData(),
(char) 0, 0,
(char) receivedPacket.getLength()); receivedPacket.getLength());
assertEquals( assertEquals(bindingResponse, receivedResponse,
"The received request did not match the one that was sent.", "The received request did not match the one that was sent.");
bindingResponse, //expected
receivedResponse); // actual
} }
/** /**
@ -272,6 +260,7 @@ public class ShallowStackTest extends TestCase
* *
* @throws Exception if something fails somewhere. * @throws Exception if something fails somewhere.
*/ */
@Test
public void testReceiveResponse() public void testReceiveResponse()
throws Exception throws Exception
{ {
@ -288,7 +277,7 @@ public class ShallowStackTest extends TestCase
collector.waitForResponse(); collector.waitForResponse();
//create the right response //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, System.arraycopy(msgFixture.bindingResponse, 0, response, 0,
response.length); response.length);
@ -310,15 +299,15 @@ public class ShallowStackTest extends TestCase
Response collectedResponse = collector.collectedResponse; Response collectedResponse = collector.collectedResponse;
byte expectedReturn[] = response; byte[] actualReturn = collectedResponse.encode(stunStack);
byte actualReturn[] = collectedResponse.encode(stunStack); assertArrayEquals(response, actualReturn,
assertTrue("Received request was not the same as the one that was sent", "Received request was not the same as the one that was sent");
Arrays.equals(expectedReturn, actualReturn));
} }
/** /**
* Verify StackProperties.FIRST_CTRAN_RETRANS_AFTER can indeed update StunClientTransaction.Retransmitter * Verify StackProperties.FIRST_CTRAN_RETRANS_AFTER can indeed update StunClientTransaction.Retransmitter
*/ */
@Test
public void testRetransmissionOriginalWait() public void testRetransmissionOriginalWait()
throws Exception throws Exception
{ {
@ -340,39 +329,36 @@ public class ShallowStackTest extends TestCase
dgramCollector.waitForPacket(); dgramCollector.waitForPacket();
DatagramPacket receivedPacket = dgramCollector.collectPacket(); DatagramPacket receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not properly send a Binding Request", assertTrue((receivedPacket.getLength() > 0),
(receivedPacket.getLength() > 0)); "The stack did not properly send a Binding Request");
Request receivedRequest = Request receivedRequest =
(Request)Request.decode(receivedPacket.getData(), (Request)Request.decode(receivedPacket.getData(),
(char)0, (char)0,
(char)receivedPacket.getLength()); (char)receivedPacket.getLength());
assertEquals("The received request did not match the " assertEquals(bindingRequest, receivedRequest,
+"one that was sent.", "The received request did not match the one that was sent.");
bindingRequest, //expected
receivedRequest); // actual
// wait for the 1st retransmission with originalWait // wait for the 1st retransmission with originalWait
dgramCollector.startListening(dummyServerSocket); dgramCollector.startListening(dummyServerSocket);
dgramCollector.waitForPacket(); dgramCollector.waitForPacket();
receivedPacket = dgramCollector.collectPacket(); receivedPacket = dgramCollector.collectPacket();
assertTrue("The stack did not retransmit a Binding Request", assertTrue((receivedPacket.getLength() > 0),
(receivedPacket.getLength() > 0)); "The stack did not retransmit a Binding Request");
receivedRequest = (Request)Request.decode( receivedRequest = (Request) Request.decode(
receivedPacket.getData(), receivedPacket.getData(),
(char)0, 0,
(char)receivedPacket.getLength()); receivedPacket.getLength());
assertEquals("The retransmitted request did not match the original.", assertEquals(bindingRequest, receivedRequest,
bindingRequest, //expected "The retransmitted request did not match the original.");
receivedRequest); // actual
// verify the retransmission is longer than the originalWait // verify the retransmission is longer than the originalWait
long secondTime = System.currentTimeMillis(); 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 --------- //--------------------------------------- listener implementations ---------

View File

@ -17,12 +17,12 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun * The StunAddressDiscovererTest_XXX set of tests were created to verify stun
* operation for scenarios of some basic types of firewalls. The purpose of * operation for scenarios of some basic types of firewalls. The purpose of
@ -34,32 +34,24 @@ import org.ice4j.stack.*;
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunAddressDiscovererTest public class StunAddressDiscovererTest
extends TestCase
{ {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null; private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null;
private TransportAddress discovererAddress private final TransportAddress discovererAddress
= new TransportAddress("127.0.0.1", 15555, Transport.UDP); = new TransportAddress("127.0.0.1", 15555, Transport.UDP);
private ResponseSequenceServer responseServer = null; private ResponseSequenceServer responseServer = null;
private TransportAddress responseServerAddress private final TransportAddress responseServerAddress
= new TransportAddress("127.0.0.1", 19999, Transport.UDP); = 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); = 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); = new TransportAddress("212.56.4.10", 15611, Transport.UDP);
public StunAddressDiscovererTest(String name) @BeforeEach
throws StunException 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_RETRANS_TIMER, "100");
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
@ -76,15 +68,14 @@ public class StunAddressDiscovererTest
responseServer.start(); 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_RETRANS_TIMER);
System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
responseServer.shutDown(); responseServer.shutDown();
stunAddressDiscoverer.shutDown(); stunAddressDiscoverer.shutDown();
stunAddressDiscoverer = null; stunAddressDiscoverer = null;
super.tearDown();
} }
/** /**
@ -93,6 +84,7 @@ public class StunAddressDiscovererTest
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeBlockedUDP() public void testRecognizeBlockedUDP()
throws Exception throws Exception
{ {
@ -104,10 +96,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals("The StunAddressDiscoverer failed for a " assertEquals(expectedReturn, actualReturn,
+"no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
@ -116,6 +106,7 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat() throws Exception public void testRecognizeSymmetricNat() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -139,10 +130,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn,
actualReturn);
} }
@ -151,6 +140,7 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Port Restricted Cone. * it concludes it is behind a Port Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizePortRestrictedCone() public void testRecognizePortRestrictedCone()
throws Exception throws Exception
{ {
@ -175,8 +165,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a no-udp environment.", assertEquals(expectedReturn, actualReturn,
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. * it concludes it is behind a Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeRestrictedCone() throws Exception public void testRecognizeRestrictedCone() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -208,10 +199,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -219,6 +208,7 @@ public class StunAddressDiscovererTest
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone() public void testRecognizeFullCone()
throws Exception throws Exception
{ {
@ -238,9 +228,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -249,6 +238,7 @@ public class StunAddressDiscovererTest
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeUdpSymmetricFirewall() public void testRecognizeUdpSymmetricFirewall()
throws Exception throws Exception
{ {
@ -267,9 +257,8 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
@ -279,6 +268,7 @@ public class StunAddressDiscovererTest
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeOpenInternet() public void testRecognizeOpenInternet()
throws Exception throws Exception
{ {
@ -298,8 +288,7 @@ public class StunAddressDiscovererTest
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
} }

View File

@ -17,12 +17,12 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* Makes basic stun tests for cases where local network addresses and the public * 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 * NAT address are using different IP versions. (e.g. Local addresses are v4
@ -38,48 +38,41 @@ import org.ice4j.stack.*;
* <p>Company: Net Research Team, Louis Pasteur University</p> * <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunAddressDiscovererTest_v4v6 extends TestCase public class StunAddressDiscovererTest_v4v6
{ {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v6 private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v6
= null; = null;
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v4 private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer_v4
= null; = null;
private TransportAddress discovererAddress_v4 private final TransportAddress discovererAddress_v4
= new TransportAddress("127.0.0.1", 17555, Transport.UDP); = new TransportAddress("127.0.0.1", 17555, Transport.UDP);
private TransportAddress discovererAddress_v6 private final TransportAddress discovererAddress_v6
= new TransportAddress("::1", 17555, Transport.UDP); = new TransportAddress("::1", 17555, Transport.UDP);
private ResponseSequenceServer responseServer_v6 = null; private ResponseSequenceServer responseServer_v6 = null;
private ResponseSequenceServer responseServer_v4 = null; private ResponseSequenceServer responseServer_v4 = null;
private TransportAddress responseServerAddress_v6 private final TransportAddress responseServerAddress_v6
= new TransportAddress("::1", 21999, Transport.UDP); = new TransportAddress("::1", 21999, Transport.UDP);
private TransportAddress responseServerAddress_v4 private final TransportAddress responseServerAddress_v4
= new TransportAddress("127.0.0.1", 21999, Transport.UDP); = 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); "2001:660:4701:1001:ff::1", 17612, Transport.UDP);
private TransportAddress mappedClientAddress_v6_Port2 private final TransportAddress mappedClientAddress_v6_Port2
= new TransportAddress( = new TransportAddress(
"2001:660:4701:1001:ff::1", 17611, Transport.UDP); "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); = 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); = new TransportAddress("130.79.99.55", 17611, Transport.UDP);
public StunAddressDiscovererTest_v4v6(String name) @BeforeEach
throws StunException public void setUp()
{
super(name);
}
protected void setUp()
throws Exception throws Exception
{ {
super.setUp();
StunStack stunStack = new StunStack(); StunStack stunStack = new StunStack();
responseServer_v6 responseServer_v6
@ -105,7 +98,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2");
} }
protected void tearDown() @AfterEach
public void tearDown()
throws Exception throws Exception
{ {
System.clearProperty(StackProperties.MAX_CTRAN_RETRANS_TIMER); 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 //give the sockets the time to clear out
Thread.sleep(1000); Thread.sleep(1000);
super.tearDown();
} }
/** /**
@ -129,6 +121,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat_Local_v6_Public_v4() public void testRecognizeSymmetricNat_Local_v6_Public_v4()
throws Exception throws Exception
{ {
@ -155,9 +148,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer_v6.determineAddress(); = stunAddressDiscoverer_v6.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a v4-v6 sym env.", assertEquals(expectedReturn, actualReturn,
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. * it concludes it is behind a Symmetric NAT.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat_Local_v4_Public_v6() throws Exception public void testRecognizeSymmetricNat_Local_v4_Public_v6() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -190,11 +183,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer_v4.determineAddress(); = stunAddressDiscoverer_v4.determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn,
actualReturn);
} }
/** /**
@ -202,6 +192,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone_Local_v6_Public_v4() throws Exception public void testRecognizeFullCone_Local_v6_Public_v4() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -224,10 +215,8 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6. StunDiscoveryReport actualReturn = stunAddressDiscoverer_v6.
determineAddress(); determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -235,6 +224,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone_Local_v4_Public_v6() throws Exception public void testRecognizeFullCone_Local_v4_Public_v6() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -257,9 +247,7 @@ public class StunAddressDiscovererTest_v4v6 extends TestCase
StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4. StunDiscoveryReport actualReturn = stunAddressDiscoverer_v4.
determineAddress(); determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
} }

View File

@ -17,11 +17,12 @@
*/ */
package org.ice4j.stunclient; package org.ice4j.stunclient;
import junit.framework.*; import static org.junit.jupiter.api.Assertions.*;
import org.ice4j.*; import org.ice4j.*;
import org.ice4j.message.*; import org.ice4j.message.*;
import org.ice4j.stack.*; import org.ice4j.stack.*;
import org.junit.jupiter.api.*;
/** /**
* The StunAddressDiscovererTest_XXX set of tests were created to verify stun * The StunAddressDiscovererTest_XXX set of tests were created to verify stun
@ -33,31 +34,24 @@ import org.ice4j.stack.*;
* <p>Company: Net Research Team, Louis Pasteur University</p> * <p>Company: Net Research Team, Louis Pasteur University</p>
* @author Emil Ivov * @author Emil Ivov
*/ */
public class StunAddressDiscovererTest_v6 extends TestCase public class StunAddressDiscovererTest_v6
{ {
private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null; private NetworkConfigurationDiscoveryProcess stunAddressDiscoverer = null;
private TransportAddress discovererAddress private final TransportAddress discovererAddress
= new TransportAddress("::1", 16555, Transport.UDP); = new TransportAddress("::1", 16555, Transport.UDP);
private ResponseSequenceServer responseServer = null; private ResponseSequenceServer responseServer = null;
private TransportAddress responseServerAddress private final TransportAddress responseServerAddress
= new TransportAddress("::1", 20999, Transport.UDP); = 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); "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); "2001:660:4701:1001:ff::1", 16611, Transport.UDP);
public StunAddressDiscovererTest_v6(String name) @BeforeEach
throws StunException public void setUp() throws Exception
{ {
super(name);
}
protected void setUp() throws Exception
{
super.setUp();
StunStack stunStack = new StunStack(); StunStack stunStack = new StunStack();
responseServer responseServer
@ -74,15 +68,14 @@ public class StunAddressDiscovererTest_v6 extends TestCase
System.setProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS, "2"); 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_RETRANS_TIMER);
System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS); System.clearProperty(StackProperties.MAX_CTRAN_RETRANSMISSIONS);
responseServer.shutDown(); responseServer.shutDown();
stunAddressDiscoverer.shutDown(); stunAddressDiscoverer.shutDown();
stunAddressDiscoverer = null; 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. * it concludes it's in a network where UDP is blocked.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeBlockedUDP() public void testRecognizeBlockedUDP()
throws Exception throws Exception
{ {
@ -101,20 +95,17 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn,
actualReturn);
} }
/** /**
* Performs a test where no responces are given the stun client so that * Performs a test where no responces are given the stun client so that
* it concludes it is behind a Symmetric NAT. * it concludes it is behind a Symmetric NAT.
* *
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeSymmetricNat() public void testRecognizeSymmetricNat()
throws Exception throws Exception
{ {
@ -139,10 +130,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals("The StunAddressDiscoverer failed for a " assertEquals(expectedReturn, actualReturn,
+"no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -150,6 +139,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase
* it concludes it is behind a Port Restricted Cone. * it concludes it is behind a Port Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizePortRestrictedCone() public void testRecognizePortRestrictedCone()
throws Exception throws Exception
{ {
@ -174,10 +164,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals("The StunAddressDiscoverer failed for" assertEquals(expectedReturn, actualReturn,
+" a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -185,6 +173,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase
* it concludes it is behind a Restricted Cone. * it concludes it is behind a Restricted Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeRestrictedCone() public void testRecognizeRestrictedCone()
throws Exception throws Exception
{ {
@ -209,10 +198,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn StunDiscoveryReport actualReturn
= stunAddressDiscoverer.determineAddress(); = stunAddressDiscoverer.determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -220,6 +207,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase
* it concludes it is behind a Full Cone. * it concludes it is behind a Full Cone.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeFullCone() throws Exception public void testRecognizeFullCone() throws Exception
{ {
//define the server response sequence //define the server response sequence
@ -238,10 +226,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -249,6 +235,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase
* it concludes it is behind a UDP Symmetric Firewall. * it concludes it is behind a UDP Symmetric Firewall.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeUdpSymmetricFirewall() public void testRecognizeUdpSymmetricFirewall()
throws Exception throws Exception
{ {
@ -267,10 +254,8 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn = stunAddressDiscoverer StunDiscoveryReport actualReturn = stunAddressDiscoverer
.determineAddress(); .determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
/** /**
@ -278,6 +263,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase
* it concludes it is behind a Open Internet. * it concludes it is behind a Open Internet.
* @throws Exception if anything goes wrong ( surprised? ). * @throws Exception if anything goes wrong ( surprised? ).
*/ */
@Test
public void testRecognizeOpenInternet() public void testRecognizeOpenInternet()
throws Exception throws Exception
{ {
@ -297,9 +283,7 @@ public class StunAddressDiscovererTest_v6 extends TestCase
StunDiscoveryReport actualReturn = stunAddressDiscoverer. StunDiscoveryReport actualReturn = stunAddressDiscoverer.
determineAddress(); determineAddress();
assertEquals( assertEquals(expectedReturn, actualReturn,
"The StunAddressDiscoverer failed for a no-udp environment.", "The StunAddressDiscoverer failed for a no-udp environment.");
expectedReturn, actualReturn);
} }
} }

View File

@ -1,9 +1,12 @@
package org.ice4j.util; package org.ice4j.util;
import org.junit.*; import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.time.*; import java.time.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import org.jitsi.test.concurrent.*;
import org.junit.jupiter.api.*;
/** /**
* Test various aspects of {@link PeriodicRunnable} implementation. * Test various aspects of {@link PeriodicRunnable} implementation.
@ -12,39 +15,52 @@ import java.util.concurrent.*;
*/ */
public class PeriodicRunnableTests 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 @Test
public void scheduleExecutesSpecifiedRunnableMultipleTimes() public void scheduleExecutesSpecifiedRunnableMultipleTimes()
throws InterruptedException
{ {
final ScheduledExecutorService timer int scheduleCount = 10;
= Executors.newSingleThreadScheduledExecutor(); Duration period = Duration.ofMillis(100);
final ExecutorService executor = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(scheduleCount);
final CountDownLatch latch = new CountDownLatch(10);
final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create(
timer, timer,
executor, executor,
Duration.ofMillis(100), period,
latch::countDown); latch::countDown);
scheduledRunnable.schedule(); scheduledRunnable.schedule();
// Give 20 extra milliseconds to avoid possible failures due to for (int i = 0; i < scheduleCount; i++)
// slight timer inaccuracy {
latch.await(1020, TimeUnit.MILLISECONDS); timer.getClock().elapse(period.plusMillis(10));
Assert.assertEquals(0, latch.getCount()); timer.run();
}
scheduledRunnable.cancel(); assertEquals(0, latch.getCount());
executor.shutdownNow();
timer.shutdownNow();
} }
@Test @Test
public void scheduleWithNegativeDelayDoesNotExecuteRunnable() public void scheduleWithNegativeDelayDoesNotExecuteRunnable()
throws InterruptedException
{ {
final ScheduledExecutorService timer
= Executors.newSingleThreadScheduledExecutor();
final ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(1);
final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create(
timer, timer,
@ -54,22 +70,16 @@ public class PeriodicRunnableTests
scheduledRunnable.schedule(); scheduledRunnable.schedule();
latch.await(1000, TimeUnit.MILLISECONDS); timer.getClock().elapse(Duration.ofSeconds(1));
Assert.assertEquals(1, latch.getCount()); timer.run();
assertEquals(1, latch.getCount());
scheduledRunnable.cancel();
executor.shutdownNow();
timer.shutdownNow();
} }
@Test @Test
public void negativeDelayStopsFurtherExecution() public void negativeDelayStopsFurtherExecution()
throws InterruptedException
{ {
final ScheduledExecutorService timer int scheduleCount = 5;
= Executors.newSingleThreadScheduledExecutor(); final CountDownLatch latch = new CountDownLatch(scheduleCount);
final ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch latch = new CountDownLatch(5);
final PeriodicRunnable scheduledRunnable = final PeriodicRunnable scheduledRunnable =
new PeriodicRunnable(timer, executor) new PeriodicRunnable(timer, executor)
{ {
@ -88,21 +98,18 @@ public class PeriodicRunnableTests
scheduledRunnable.schedule(); scheduledRunnable.schedule();
latch.await(1000, TimeUnit.MILLISECONDS); for (int i = 0; i < scheduleCount; i++)
Assert.assertEquals(1, latch.getCount()); {
timer.getClock().elapse(Duration.ofMillis(100));
timer.run();
}
scheduledRunnable.cancel(); assertEquals(1, latch.getCount());
executor.shutdownNow();
timer.shutdownNow();
} }
@Test @Test
public void cancelStopFurtherExecution() public void cancelStopFurtherExecution()
throws InterruptedException
{ {
final ScheduledExecutorService timer
= Executors.newSingleThreadScheduledExecutor();
final ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch latch = new CountDownLatch(2); final CountDownLatch latch = new CountDownLatch(2);
final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create(
timer, timer,
@ -111,30 +118,24 @@ public class PeriodicRunnableTests
latch::countDown); latch::countDown);
scheduledRunnable.schedule(); scheduledRunnable.schedule();
latch.await(520, TimeUnit.MILLISECONDS); timer.getClock().elapse(Duration.ofMillis(520));
timer.run();
// Check runnable executed once // Check runnable executed once
Assert.assertEquals(1, latch.getCount()); assertEquals(1, latch.getCount());
scheduledRunnable.cancel(); scheduledRunnable.cancel();
latch.await(1000, TimeUnit.MILLISECONDS); timer.getClock().elapse(Duration.ofSeconds(1));
timer.run();
// Check runnable was not executed after cancel. // Check runnable was not executed after cancel.
Assert.assertEquals(1, latch.getCount()); assertEquals(1, latch.getCount());
scheduledRunnable.cancel();
executor.shutdownNow();
timer.shutdownNow();
} }
@Test @Test
public void scheduleExecuteRunnableIfPreviouslyCancelled() public void scheduleExecuteRunnableIfPreviouslyCancelled()
throws InterruptedException
{ {
final ScheduledExecutorService timer final CountDownLatch latch = new CountDownLatch(10);
= Executors.newSingleThreadScheduledExecutor();
final ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch latch = new CountDownLatch(5);
final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create( final PeriodicRunnable scheduledRunnable = PeriodicRunnable.create(
timer, timer,
executor, executor,
@ -142,24 +143,26 @@ public class PeriodicRunnableTests
latch::countDown); latch::countDown);
scheduledRunnable.schedule(); scheduledRunnable.schedule();
latch.await(220, TimeUnit.MILLISECONDS); timer.getClock().elapse(Duration.ofMillis(220));
timer.run();
// Check runnable executed once // Check runnable executed once
Assert.assertEquals(4, latch.getCount()); assertEquals(9, latch.getCount());
scheduledRunnable.cancel(); scheduledRunnable.cancel();
latch.await(1000, TimeUnit.MILLISECONDS); timer.getClock().elapse(Duration.ofSeconds(1));
timer.run();
// Check runnable was not executed after cancel. // Check runnable was not executed after cancel.
Assert.assertEquals(4, latch.getCount()); assertEquals(9, latch.getCount());
// Schedule again // Schedule again
scheduledRunnable.schedule(); scheduledRunnable.schedule();
latch.await(1000, TimeUnit.MILLISECONDS); for (int i = 0; i < 5; i++)
Assert.assertEquals(0, latch.getCount()); {
timer.getClock().elapse(Duration.ofMillis(200));
scheduledRunnable.cancel(); timer.run();
executor.shutdownNow(); }
timer.shutdownNow(); assertEquals(4, latch.getCount());
} }
} }

View File

@ -38,5 +38,5 @@ abstract class ConfigTest : ShouldSpec() {
useNewConfig("new-${this::class.simpleName}", config, true, block) useNewConfig("new-${this::class.simpleName}", config, true, block)
} }
fun withLegacyConfig(config: Map<String,String?>, block: () -> Unit) = withSystemProperties(config) { block } fun withLegacyConfig(config: Map<String, String?>, block: () -> Unit) = withSystemProperties(config) { block }
} }

View File

@ -73,7 +73,8 @@ private val legacyConfig = mapOf(
"org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL" to "5000", "org.ice4j.ice.CONSENT_FRESHNESS_WAIT_INTERVAL" to "5000",
"org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS" to "5000", "org.ice4j.ice.CONSENT_FRESHNESS_MAX_RETRANSMISSIONS" to "5000",
"org.ice4j.TERMINATION_DELAY" 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 = """ private val newConfig = """
ice4j.consent-freshness.interval = 6 seconds ice4j.consent-freshness.interval = 6 seconds

View File

@ -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());
}
}