diff --git a/.github/workflows/publish-snapshot.yml b/.github/workflows/publish-snapshot.yml new file mode 100644 index 0000000000..2b6e5be866 --- /dev/null +++ b/.github/workflows/publish-snapshot.yml @@ -0,0 +1,33 @@ +name: Publish snapshot + +on: workflow_dispatch + +jobs: + build: + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + cache: 'maven' + server-id: ossrh + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + - name: Get dependencies + run: make deps + - name: Publish snapshot + run: ./mvnw clean deploy -Psnapshots -DskipITs -DskipTests --no-transfer-progress + env: + MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000000..f69d596fd4 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,50 @@ +name: Release AMQP Java Client + +on: + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + - name: Evaluate release type + run: ci/evaluate-release.sh + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '8' + cache: 'maven' + server-id: ${{ env.maven_server_id }} + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + - name: Get dependencies + run: make deps + - name: Release AMQP Java Client (GA) + if: ${{ env.ga_release == 'true' }} + run: | + git config user.name "rabbitmq-ci" + git config user.email "rabbitmq-ci@users.noreply.github.com" + ci/release-java-client.sh + env: + MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + - name: Release AMQP Java Client (Milestone/RC) + if: ${{ env.ga_release != 'true' }} + run: | + git config user.name "rabbitmq-ci" + git config user.email "rabbitmq-ci@users.noreply.github.com" + ci/release-java-client.sh + env: + MAVEN_USERNAME: '' + MAVEN_PASSWORD: ${{ secrets.PACKAGECLOUD_TOKEN }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file diff --git a/.github/workflows/test-native-image.yml b/.github/workflows/test-native-image.yml new file mode 100644 index 0000000000..e92fe19b11 --- /dev/null +++ b/.github/workflows/test-native-image.yml @@ -0,0 +1,66 @@ +name: Test GraalVM native image + +on: + schedule: + - cron: '0 4 ? * SUN,THU' + workflow_dispatch: + +env: + RABBITMQ_IMAGE: 'rabbitmq:3.11' + +jobs: + build: + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + - name: Checkout tls-gen + uses: actions/checkout@v3 + with: + repository: rabbitmq/tls-gen + path: './tls-gen' + - name: Checkout GraalVM test project + uses: actions/checkout@v3 + with: + repository: rabbitmq/rabbitmq-graal-vm-test + path: './rabbitmq-graal-vm-test' + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up GraalVM + uses: graalvm/setup-graalvm@v1 + with: + version: 'latest' + java-version: '17' + components: 'native-image' + cache: 'maven' + - name: Start broker + run: ci/start-broker.sh + - name: Get dependencies + run: make deps + - name: Install client JAR file + run: | + ./mvnw clean install -Psnapshots -DskipITs -DskipTests -Dgpg.skip=true --no-transfer-progress + export ARTEFACT_VERSION=$(cat pom.xml | grep -oPm1 "(?<=)[^<]+") + echo "artefact_version=$ARTEFACT_VERSION" >> $GITHUB_ENV + - name: Package test application + working-directory: rabbitmq-graal-vm-test + run: | + ./mvnw --version + echo "Using RabbitMQ Java Client ${{ env.artefact_version }}" + ./mvnw -q clean package -Damqp-client.version=${{ env.artefact_version }} --no-transfer-progress + - name: Start one-time RPC server + working-directory: rabbitmq-graal-vm-test + run: ./mvnw -q compile exec:java -Damqp-client.version=${{ env.artefact_version }} --no-transfer-progress & + - name: Create native image + working-directory: rabbitmq-graal-vm-test + run: | + native-image -jar target/rabbitmq-graal-vm-test-full.jar \ + --initialize-at-build-time=com.rabbitmq.client \ + --initialize-at-build-time=org.slf4j --no-fallback + - name: Use native image program + working-directory: rabbitmq-graal-vm-test + run: ./rabbitmq-graal-vm-test-full + - name: Stop broker + run: docker stop rabbitmq && docker rm rabbitmq diff --git a/.github/workflows/test-rabbitmq-alphas.yml b/.github/workflows/test-rabbitmq-alphas.yml new file mode 100644 index 0000000000..2e25fd5e00 --- /dev/null +++ b/.github/workflows/test-rabbitmq-alphas.yml @@ -0,0 +1,61 @@ +name: Test against RabbitMQ alphas + +on: + schedule: + - cron: '0 4 ? * SUN,THU' + pull_request: + branches: + - 5.x.x-stable + push: + branches: + - 5.x.x-stable + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-22.04 + strategy: + matrix: + rabbitmq-image: [ 'pivotalrabbitmq/rabbitmq:v3.11.x-otp-max-bazel', 'pivotalrabbitmq/rabbitmq:v3.12.x-otp-max-bazel' ] + name: Test against ${{ matrix.rabbitmq-image }} + steps: + - uses: actions/checkout@v3 + - name: Checkout tls-gen + uses: actions/checkout@v3 + with: + repository: rabbitmq/tls-gen + path: './tls-gen' + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + cache: 'maven' + - name: Start cluster + run: ci/start-cluster.sh + env: + RABBITMQ_IMAGE: ${{ matrix.rabbitmq-image }} + - name: Get dependencies + run: make deps + - name: Test with NIO + run: | + ./mvnw verify -P '!setup-test-cluster,use-nio' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dtest-broker.B.nodename=hare@$(hostname) \ + -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + --no-transfer-progress + - name: Test with blocking IO + run: | + ./mvnw verify -P '!setup-test-cluster' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dtest-broker.B.nodename=hare@$(hostname) \ + -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + --no-transfer-progress + - name: Stop broker A + run: docker stop rabbitmq && docker rm rabbitmq + - name: Stop broker B + run: docker stop hare && docker rm hare diff --git a/.github/workflows/test-supported-java-versions-5.x.yml b/.github/workflows/test-supported-java-versions-5.x.yml new file mode 100644 index 0000000000..5696a4db3d --- /dev/null +++ b/.github/workflows/test-supported-java-versions-5.x.yml @@ -0,0 +1,58 @@ +name: Test against supported Java versions (5.x) + +on: + schedule: + - cron: '0 4 ? * SUN,THU' + workflow_dispatch: + +env: + RABBITMQ_IMAGE: 'rabbitmq:3.11' + +jobs: + build: + runs-on: ubuntu-22.04 + strategy: + matrix: + java: [ '8', '11', '17', '19', '20-ea' ] + name: Test against Java ${{ matrix.java }} + steps: + - uses: actions/checkout@v3 + with: + ref: 5.x.x-stable + - name: Checkout tls-gen + uses: actions/checkout@v3 + with: + repository: rabbitmq/tls-gen + path: './tls-gen' + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: ${{ matrix.java }} + cache: 'maven' + - name: Start broker + run: ci/start-broker.sh + - name: Get dependencies + run: make deps + - name: Show version + run: ./mvnw --version + - name: Test with NIO + run: | + ./mvnw verify -P '!setup-test-cluster,use-nio' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + -Dit.test=ClientTestSuite,FunctionalTestSuite,ServerTestSuite,SslTestSuite \ + --no-transfer-progress + - name: Test with blocking IO + run: | + ./mvnw verify -P '!setup-test-cluster' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + -Dit.test=ClientTestSuite,FunctionalTestSuite,ServerTestSuite,SslTestSuite \ + --no-transfer-progress + - name: Stop broker + run: docker stop rabbitmq && docker rm rabbitmq diff --git a/.github/workflows/test-supported-java-versions-main.yml b/.github/workflows/test-supported-java-versions-main.yml new file mode 100644 index 0000000000..6d8b473a09 --- /dev/null +++ b/.github/workflows/test-supported-java-versions-main.yml @@ -0,0 +1,56 @@ +name: Test against supported Java versions (main) + +on: + schedule: + - cron: '0 4 ? * SUN,THU' + workflow_dispatch: + +env: + RABBITMQ_IMAGE: 'rabbitmq:3.11' + +jobs: + build: + runs-on: ubuntu-22.04 + strategy: + matrix: + java: [ '8', '11', '17', '19', '20-ea' ] + name: Test against Java ${{ matrix.java }} + steps: + - uses: actions/checkout@v3 + - name: Checkout tls-gen + uses: actions/checkout@v3 + with: + repository: rabbitmq/tls-gen + path: './tls-gen' + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'zulu' + java-version: ${{ matrix.java }} + cache: 'maven' + - name: Start broker + run: ci/start-broker.sh + - name: Get dependencies + run: make deps + - name: Show version + run: ./mvnw --version + - name: Test with NIO + run: | + ./mvnw verify -P '!setup-test-cluster,use-nio' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + -Dit.test=ClientTestSuite,FunctionalTestSuite,ServerTestSuite,SslTestSuite \ + --no-transfer-progress + - name: Test with blocking IO + run: | + ./mvnw verify -P '!setup-test-cluster' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + -Dit.test=ClientTestSuite,FunctionalTestSuite,ServerTestSuite,SslTestSuite \ + --no-transfer-progress + - name: Stop broker + run: docker stop rabbitmq && docker rm rabbitmq diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000000..447fb58a29 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,66 @@ +name: Test against RabbitMQ 3.12 stable + +on: + pull_request: + branches: + - 5.17.x-stable + push: + branches: + - 5.17.x-stable + workflow_dispatch: + +jobs: + build: + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + - name: Checkout tls-gen + uses: actions/checkout@v3 + with: + repository: rabbitmq/tls-gen + path: './tls-gen' + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.x' + - name: Set up JDK + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '17' + cache: 'maven' + server-id: ossrh + server-username: MAVEN_USERNAME + server-password: MAVEN_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + - name: Start cluster + run: ci/start-cluster.sh + - name: Get dependencies + run: make deps + - name: Test with NIO + run: | + ./mvnw verify -P '!setup-test-cluster,use-nio' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dtest-broker.B.nodename=hare@$(hostname) \ + -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + --no-transfer-progress + - name: Test with blocking IO + run: | + ./mvnw verify -P '!setup-test-cluster' -Drabbitmqctl.bin=DOCKER:rabbitmq \ + -Dtest-broker.A.nodename=rabbit@$(hostname) -Dtest-broker.B.nodename=hare@$(hostname) \ + -Dmaven.javadoc.skip=true \ + -Dtest-client-cert.password= -Dtest-tls-certs.dir=rabbitmq-configuration/tls \ + --no-transfer-progress + - name: Stop broker A + run: docker stop rabbitmq && docker rm rabbitmq + - name: Stop broker B + run: docker stop hare && docker rm hare + - name: Publish snapshot + if: ${{ github.event_name != 'pull_request' }} + run: ./mvnw clean deploy -Psnapshots -DskipITs -DskipTests --no-transfer-progress + env: + MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }} + MAVEN_PASSWORD: ${{ secrets.OSSRH_TOKEN }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} diff --git a/.mvn/maven.config b/.mvn/maven.config new file mode 100644 index 0000000000..f373d1de10 --- /dev/null +++ b/.mvn/maven.config @@ -0,0 +1 @@ +-Dmaven.wagon.http.retryHandler.count=10 diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 642d572ce9..a9f1ef87bb 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,2 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.3/apache-maven-3.8.3-bin.zip wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/ci/evaluate-release.sh b/ci/evaluate-release.sh new file mode 100755 index 0000000000..4ad656d7a0 --- /dev/null +++ b/ci/evaluate-release.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +source ./release-versions.txt + +if [[ $RELEASE_VERSION == *[RCM]* ]] +then + echo "prerelease=true" >> $GITHUB_ENV + echo "ga_release=false" >> $GITHUB_ENV + echo "maven_server_id=packagecloud-rabbitmq-maven-milestones" >> $GITHUB_ENV +else + echo "prerelease=false" >> $GITHUB_ENV + echo "ga_release=true" >> $GITHUB_ENV + echo "maven_server_id=ossrh" >> $GITHUB_ENV +fi \ No newline at end of file diff --git a/ci/release-java-client.sh b/ci/release-java-client.sh new file mode 100755 index 0000000000..d3fd7df952 --- /dev/null +++ b/ci/release-java-client.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash + +source ./release-versions.txt +git checkout $RELEASE_BRANCH + +./mvnw release:clean release:prepare -DdryRun=true -Darguments="-DskipTests" --no-transfer-progress \ + --batch-mode -Dtag="v$RELEASE_VERSION" \ + -DreleaseVersion=$RELEASE_VERSION \ + -DdevelopmentVersion=$DEVELOPMENT_VERSION \ + +./mvnw release:clean release:prepare -Darguments="-DskipTests" --no-transfer-progress \ + --batch-mode -Dtag="v$RELEASE_VERSION" \ + -DreleaseVersion=$RELEASE_VERSION \ + -DdevelopmentVersion=$DEVELOPMENT_VERSION + +git checkout "v$RELEASE_VERSION" + +if [[ $RELEASE_VERSION == *[RCM]* ]] +then + MAVEN_PROFILE="milestone" + echo "prerelease=true" >> $GITHUB_ENV +else + MAVEN_PROFILE="release" + echo "prerelease=false" >> $GITHUB_ENV +fi + +./mvnw clean deploy -P $MAVEN_PROFILE -DskipTests --no-transfer-progress \ No newline at end of file diff --git a/ci/start-broker.sh b/ci/start-broker.sh new file mode 100755 index 0000000000..8ad81bb837 --- /dev/null +++ b/ci/start-broker.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +LOCAL_SCRIPT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +RABBITMQ_IMAGE=${RABBITMQ_IMAGE:-rabbitmq:3.12} + +wait_for_message() { + while ! docker logs "$1" | grep -q "$2"; + do + sleep 5 + echo "Waiting 5 seconds for $1 to start..." + done +} + +make -C "${PWD}"/tls-gen/basic + +mv tls-gen/basic/result/server_$(hostname -s)_certificate.pem tls-gen/basic/result/server_certificate.pem +mv tls-gen/basic/result/server_$(hostname -s)_key.pem tls-gen/basic/result/server_key.pem +mv tls-gen/basic/server_$(hostname -s) tls-gen/basic/server +mv tls-gen/basic/client_$(hostname -s) tls-gen/basic/client + +mkdir -p rabbitmq-configuration/tls + +cp -R "${PWD}"/tls-gen/basic/* rabbitmq-configuration/tls +chmod -R o+r rabbitmq-configuration/tls/* +./mvnw -q clean resources:testResources -Dtest-tls-certs.dir=/etc/rabbitmq/tls +cp target/test-classes/rabbit@localhost.config rabbitmq-configuration/rabbitmq.config + +echo "Running RabbitMQ ${RABBITMQ_IMAGE}" + +docker rm -f rabbitmq 2>/dev/null || echo "rabbitmq was not running" +docker run -d --name rabbitmq \ + --network host \ + -v "${PWD}"/rabbitmq-configuration:/etc/rabbitmq \ + "${RABBITMQ_IMAGE}" + +wait_for_message rabbitmq "completed with" + +docker exec rabbitmq rabbitmq-diagnostics erlang_version +docker exec rabbitmq rabbitmqctl version diff --git a/ci/start-cluster.sh b/ci/start-cluster.sh new file mode 100755 index 0000000000..f855daaf93 --- /dev/null +++ b/ci/start-cluster.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash + +LOCAL_SCRIPT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +RABBITMQ_IMAGE=${RABBITMQ_IMAGE:-rabbitmq:3.12} + +wait_for_message() { + while ! docker logs "$1" | grep -q "$2"; + do + sleep 5 + echo "Waiting 5 seconds for $1 to start..." + done +} + +make -C "${PWD}"/tls-gen/basic + +mv tls-gen/basic/result/server_$(hostname -s)_certificate.pem tls-gen/basic/result/server_certificate.pem +mv tls-gen/basic/result/server_$(hostname -s)_key.pem tls-gen/basic/result/server_key.pem +mv tls-gen/basic/server_$(hostname -s) tls-gen/basic/server +mv tls-gen/basic/client_$(hostname -s) tls-gen/basic/client + +mkdir -p rabbitmq-configuration/tls + +cp -R "${PWD}"/tls-gen/basic/* rabbitmq-configuration/tls +chmod -R o+r rabbitmq-configuration/tls/* +./mvnw -q clean resources:testResources -Dtest-tls-certs.dir=/etc/rabbitmq/tls +cp target/test-classes/rabbit@localhost.config rabbitmq-configuration/rabbit@localhost.config +cp target/test-classes/hare@localhost.config rabbitmq-configuration/hare@localhost.config + +echo "Running RabbitMQ ${RABBITMQ_IMAGE}" + +docker rm -f rabbitmq 2>/dev/null || echo "rabbitmq was not running" +docker run -d --name rabbitmq \ + --network host \ + -v "${PWD}"/rabbitmq-configuration:/etc/rabbitmq \ + --env RABBITMQ_CONFIG_FILE=/etc/rabbitmq/rabbit@localhost.config \ + --env RABBITMQ_NODENAME=rabbit@$(hostname) \ + --env RABBITMQ_NODE_PORT=5672 \ + --env RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS="-setcookie do-not-do-this-in-production" \ + "${RABBITMQ_IMAGE}" + +# for CLI commands to share the same cookie +docker exec rabbitmq bash -c "echo 'do-not-do-this-in-production' > /var/lib/rabbitmq/.erlang.cookie" +docker exec rabbitmq chmod 0600 /var/lib/rabbitmq/.erlang.cookie + +wait_for_message rabbitmq "completed with" + +docker run -d --name hare \ + --network host \ + -v "${PWD}"/rabbitmq-configuration:/etc/rabbitmq \ + --env RABBITMQ_CONFIG_FILE=/etc/rabbitmq/hare@localhost.config \ + --env RABBITMQ_NODENAME=hare@$(hostname) \ + --env RABBITMQ_NODE_PORT=5673 \ + --env RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS="-setcookie do-not-do-this-in-production" \ + "${RABBITMQ_IMAGE}" + +# for CLI commands to share the same cookie +docker exec hare bash -c "echo 'do-not-do-this-in-production' > /var/lib/rabbitmq/.erlang.cookie" +docker exec hare chmod 0600 /var/lib/rabbitmq/.erlang.cookie + +wait_for_message hare "completed with" + +docker exec hare rabbitmqctl --node hare@$(hostname) status + +docker exec rabbitmq rabbitmq-diagnostics --node rabbit@$(hostname) is_running +docker exec hare rabbitmq-diagnostics --node hare@$(hostname) is_running + +docker exec hare rabbitmqctl --node hare@$(hostname) stop_app +docker exec hare rabbitmqctl --node hare@$(hostname) join_cluster rabbit@$(hostname) +docker exec hare rabbitmqctl --node hare@$(hostname) start_app + +sleep 10 + +docker exec hare rabbitmqctl --node hare@$(hostname) await_startup + +docker exec rabbitmq rabbitmq-diagnostics --node rabbit@$(hostname) erlang_version +docker exec rabbitmq rabbitmqctl --node rabbit@$(hostname) version +docker exec rabbitmq rabbitmqctl --node rabbit@$(hostname) status +docker exec rabbitmq rabbitmqctl --node rabbit@$(hostname) cluster_status diff --git a/deploy-javadoc.sh b/deploy-javadoc.sh index 74878215e9..46cdb09398 100755 --- a/deploy-javadoc.sh +++ b/deploy-javadoc.sh @@ -5,6 +5,11 @@ TAG=$(git describe --exact-match --tags $(git log -n1 --pretty='%h')) make deps ./mvnw -q clean javadoc:javadoc -Dmaven.javadoc.failOnError=false + +if [ -e target/site/apidocs/element-list ] + then cp target/site/apidocs/element-list target/site/apidocs/package-list +fi + git co gh-pages rm -rf $DEPLOY_DIRECTORY/* cp -r target/site/apidocs/* $DEPLOY_DIRECTORY diff --git a/pom.xml b/pom.xml index f9c92a513d..b57a295f38 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.rabbitmq amqp-client - 5.13.0-SNAPSHOT + 5.17.2-SNAPSHOT jar RabbitMQ Java Client @@ -13,7 +13,7 @@ - ASL 2.0 + AL 2.0 https://www.apache.org/licenses/LICENSE-2.0.html repo @@ -45,7 +45,7 @@ HEAD - + VMware, Inc. or its affiliates. https://www.rabbitmq.com @@ -54,35 +54,38 @@ UTF-8 UTF-8 - 1.7.31 - 4.2.2 - 1.7.1 - 2.12.3 - 1.2.3 - 4.13.2 - 3.11.2 - 3.20.2 - 9.4.42.v20210604 - 1.69 - - 3.2.0 - 2.5.3 - 2.3 - 3.1.0 - 3.0.1 - 2.0 - 2.4.8 - 1.5 - 1.12 - 3.8.1 - 2.22.2 - 2.22.2 - 1.6 - 3.0.2 - 3.2.0 + 1.7.36 + 4.2.17 + 1.10.5 + 1.24.0 + 2.14.1 + 1.2.11 + 5.9.2 + 5.2.0 + 3.24.2 + 9.4.51.v20230217 + 1.70 + 0.10 + 2.10.1 + + 3.5.0 + 3.0.0 + 2.15.0 + 3.3.0 + 3.2.1 + 2.1.1 + 2.4.21 + 1.7 + 3.3.0 + 3.11.0 + 3.0.0 + 3.0.0 + 3.0.1 + 3.3.0 + 5.1.8 0.0.6 - 1.6.8 - 1.8 + 1.6.13 + 1.11 1.3 - javadoc-no-module-dir-java-11 - - [11,) - - - --no-module-directories - - - + + org.junit.jupiter + junit-jupiter-params test @@ -759,8 +773,39 @@ ${bouncycastle.version} test + + com.github.netcrusherorg + netcrusher-core + ${netcrusher.version} + test + + + io.opentelemetry + opentelemetry-sdk-testing + ${opentelemetry.version} + test + + + com.google.code.gson + gson + ${gson.version} + test + + + + + + + org.junit + junit-bom + ${junit.jupiter.version} + pom + import + + + @@ -768,7 +813,7 @@ org.sonarsource.scanner.maven sonar-maven-plugin - 3.5.0.1254 + 3.9.1.2184 @@ -980,6 +1025,7 @@ manifest + true com.rabbitmq* com.rabbitmq.client diff --git a/release-versions.txt b/release-versions.txt index b350937ea3..71321492ca 100644 --- a/release-versions.txt +++ b/release-versions.txt @@ -1,3 +1,3 @@ -RELEASE_VERSION="5.13.0.RC2" -DEVELOPMENT_VERSION="5.13.0-SNAPSHOT" +RELEASE_VERSION="5.17.0" +DEVELOPMENT_VERSION="5.18.0-SNAPSHOT" RELEASE_BRANCH="5.x.x-stable" diff --git a/src/main/java/com/rabbitmq/client/Address.java b/src/main/java/com/rabbitmq/client/Address.java index 394f5e7b60..d86c040ba5 100644 --- a/src/main/java/com/rabbitmq/client/Address.java +++ b/src/main/java/com/rabbitmq/client/Address.java @@ -16,6 +16,7 @@ package com.rabbitmq.client; +import java.net.InetSocketAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -161,6 +162,13 @@ public static Address parseAddress(String addressString) { } } + /** + * Construct an InetSocketAddress for this address with a specific port + */ + public InetSocketAddress toInetSocketAddress(int port) { + return new InetSocketAddress(getHost(), port); + } + /** * Array-based factory method: takes an array of formatted address strings as construction parameter * @param addresses array of strings of form "host[:port],..." @@ -191,5 +199,4 @@ public static Address[] parseAddresses(String addresses) { @Override public String toString() { return _port == -1 ? _host : _host + ":" + _port; } - } diff --git a/src/main/java/com/rabbitmq/client/Channel.java b/src/main/java/com/rabbitmq/client/Channel.java index 2520858b9e..4c20cd4467 100644 --- a/src/main/java/com/rabbitmq/client/Channel.java +++ b/src/main/java/com/rabbitmq/client/Channel.java @@ -767,7 +767,7 @@ void queueDeclareNoWait(String queue, boolean durable, boolean exclusive, boolea * Reject one or several received messages. * * Supply the deliveryTag from the {@link com.rabbitmq.client.AMQP.Basic.GetOk} - * or {@link com.rabbitmq.client.AMQP.Basic.GetOk} method containing the message to be rejected. + * or {@link com.rabbitmq.client.AMQP.Basic.Deliver} method containing the message to be rejected. * @see com.rabbitmq.client.AMQP.Basic.Nack * @param deliveryTag the tag from the received {@link com.rabbitmq.client.AMQP.Basic.GetOk} or {@link com.rabbitmq.client.AMQP.Basic.Deliver} * @param multiple true to reject all messages up to and including diff --git a/src/main/java/com/rabbitmq/client/ConnectionFactory.java b/src/main/java/com/rabbitmq/client/ConnectionFactory.java index 6488be4838..92566cb2e5 100644 --- a/src/main/java/com/rabbitmq/client/ConnectionFactory.java +++ b/src/main/java/com/rabbitmq/client/ConnectionFactory.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -205,6 +205,13 @@ public class ConnectionFactory implements Cloneable { private CredentialsRefreshService credentialsRefreshService; + /** + * Maximum body size of inbound (received) messages in bytes. + * + *

Default value is 67,108,864 (64 MiB). + */ + private int maxInboundMessageBodySize = 1_048_576 * 64; + /** @return the default host to use for connections */ public String getHost() { return host; @@ -970,11 +977,15 @@ protected synchronized FrameHandlerFactory createFrameHandlerFactory() throws IO if(this.nioParams.getNioExecutor() == null && this.nioParams.getThreadFactory() == null) { this.nioParams.setThreadFactory(getThreadFactory()); } - this.frameHandlerFactory = new SocketChannelFrameHandlerFactory(connectionTimeout, nioParams, isSSL(), sslContextFactory); + this.frameHandlerFactory = new SocketChannelFrameHandlerFactory( + connectionTimeout, nioParams, isSSL(), sslContextFactory, + this.maxInboundMessageBodySize); } return this.frameHandlerFactory; } else { - return new SocketFrameHandlerFactory(connectionTimeout, socketFactory, socketConf, isSSL(), this.shutdownExecutor, sslContextFactory); + return new SocketFrameHandlerFactory(connectionTimeout, socketFactory, + socketConf, isSSL(), this.shutdownExecutor, sslContextFactory, + this.maxInboundMessageBodySize); } } @@ -1273,6 +1284,7 @@ public ConnectionParams params(ExecutorService consumerWorkServiceExecutor) { result.setRecoveredQueueNameSupplier(recoveredQueueNameSupplier); result.setTrafficListener(trafficListener); result.setCredentialsRefreshService(credentialsRefreshService); + result.setMaxInboundMessageBodySize(maxInboundMessageBodySize); return result; } @@ -1343,10 +1355,10 @@ public Connection newConnection(ExecutorService executor, String connectionName) } protected AddressResolver createAddressResolver(List

addresses) { - if(addresses.size() == 1 && !isSSL()) { - return new DnsRecordIpAddressResolver(addresses.get(0), isSSL()); - } else { + if (addresses.size() > 1) { return new ListAddressResolver(addresses); + } else { + return new DnsRecordIpAddressResolver(addresses.get(0), isSSL()); } } @@ -1556,6 +1568,21 @@ public int getChannelRpcTimeout() { return channelRpcTimeout; } + /** + * Maximum body size of inbound (received) messages in bytes. + * + *

Default value is 67,108,864 (64 MiB). + * + * @param maxInboundMessageBodySize the maximum size of inbound messages + */ + public void setMaxInboundMessageBodySize(int maxInboundMessageBodySize) { + if (maxInboundMessageBodySize <= 0) { + throw new IllegalArgumentException("Max inbound message body size must be greater than 0: " + + maxInboundMessageBodySize); + } + this.maxInboundMessageBodySize = maxInboundMessageBodySize; + } + /** * The factory to create SSL contexts. * This provides more flexibility to create {@link SSLContext}s diff --git a/src/main/java/com/rabbitmq/client/ConnectionFactoryConfigurator.java b/src/main/java/com/rabbitmq/client/ConnectionFactoryConfigurator.java index d59770380e..66f4a3742d 100644 --- a/src/main/java/com/rabbitmq/client/ConnectionFactoryConfigurator.java +++ b/src/main/java/com/rabbitmq/client/ConnectionFactoryConfigurator.java @@ -210,7 +210,7 @@ public static void load(ConnectionFactory cf, Map properties, St } String topologyRecovery = lookUp(TOPOLOGY_RECOVERY_ENABLED, properties, prefix); if (topologyRecovery != null) { - cf.setTopologyRecoveryEnabled(Boolean.getBoolean(topologyRecovery)); + cf.setTopologyRecoveryEnabled(Boolean.valueOf(topologyRecovery)); } String networkRecoveryInterval = lookUp(CONNECTION_RECOVERY_INTERVAL, properties, prefix); if (networkRecoveryInterval != null) { diff --git a/src/main/java/com/rabbitmq/client/DnsRecordIpAddressResolver.java b/src/main/java/com/rabbitmq/client/DnsRecordIpAddressResolver.java index 2f9ce570a4..9c5d0dc69f 100644 --- a/src/main/java/com/rabbitmq/client/DnsRecordIpAddressResolver.java +++ b/src/main/java/com/rabbitmq/client/DnsRecordIpAddressResolver.java @@ -72,9 +72,9 @@ public List

getAddresses() throws UnknownHostException { InetAddress[] inetAddresses = resolveIpAddresses(hostName); - List
addresses = new ArrayList
(); + List
addresses = new ArrayList<>(); for (InetAddress inetAddress : inetAddresses) { - addresses.add(new Address(inetAddress.getHostAddress(), portNumber)); + addresses.add(new ResolvedInetAddress(hostName, inetAddress, portNumber)); } return addresses; } diff --git a/src/main/java/com/rabbitmq/client/ResolvedInetAddress.java b/src/main/java/com/rabbitmq/client/ResolvedInetAddress.java new file mode 100644 index 0000000000..ca72abda81 --- /dev/null +++ b/src/main/java/com/rabbitmq/client/ResolvedInetAddress.java @@ -0,0 +1,18 @@ +package com.rabbitmq.client; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +public class ResolvedInetAddress extends Address { + private final InetAddress inetAddress; + + public ResolvedInetAddress(String originalHostname, InetAddress inetAddress, int port) { + super(originalHostname, port); + this.inetAddress = inetAddress; + } + + @Override + public InetSocketAddress toInetSocketAddress(int port) { + return new InetSocketAddress(inetAddress, port); + } +} diff --git a/src/main/java/com/rabbitmq/client/impl/AMQChannel.java b/src/main/java/com/rabbitmq/client/impl/AMQChannel.java index fe64ab370e..f863edfd3a 100644 --- a/src/main/java/com/rabbitmq/client/impl/AMQChannel.java +++ b/src/main/java/com/rabbitmq/client/impl/AMQChannel.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -62,7 +62,7 @@ public abstract class AMQChannel extends ShutdownNotifierComponent { private final int _channelNumber; /** Command being assembled */ - private AMQCommand _command = new AMQCommand(); + private AMQCommand _command; /** The current outstanding RPC request, if any. (Could become a queue in future.) */ private RpcWrapper _activeRpc = null; @@ -76,6 +76,7 @@ public abstract class AMQChannel extends ShutdownNotifierComponent { private final boolean _checkRpcResponseType; private final TrafficListener _trafficListener; + private final int maxInboundMessageBodySize; /** * Construct a channel on the given connection, with the given channel number. @@ -91,6 +92,8 @@ public AMQChannel(AMQConnection connection, int channelNumber) { this._rpcTimeout = connection.getChannelRpcTimeout(); this._checkRpcResponseType = connection.willCheckRpcResponseType(); this._trafficListener = connection.getTrafficListener(); + this.maxInboundMessageBodySize = connection.getMaxInboundMessageBodySize(); + this._command = new AMQCommand(this.maxInboundMessageBodySize); } /** @@ -110,7 +113,7 @@ public int getChannelNumber() { public void handleFrame(Frame frame) throws IOException { AMQCommand command = _command; if (command.handleFrame(frame)) { // a complete command has rolled off the assembly line - _command = new AMQCommand(); // prepare for the next one + _command = new AMQCommand(this.maxInboundMessageBodySize); // prepare for the next one handleCompleteInboundCommand(command); } } diff --git a/src/main/java/com/rabbitmq/client/impl/AMQCommand.java b/src/main/java/com/rabbitmq/client/impl/AMQCommand.java index b8cb3c97dd..a761e5cce6 100644 --- a/src/main/java/com/rabbitmq/client/impl/AMQCommand.java +++ b/src/main/java/com/rabbitmq/client/impl/AMQCommand.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -44,9 +44,13 @@ public class AMQCommand implements Command { /** The assembler for this command - synchronised on - contains all the state */ private final CommandAssembler assembler; + AMQCommand(int maxBodyLength) { + this(null, null, null, maxBodyLength); + } + /** Construct a command ready to fill in by reading frames */ public AMQCommand() { - this(null, null, null); + this(null, null, null, Integer.MAX_VALUE); } /** @@ -54,7 +58,7 @@ public AMQCommand() { * @param method the wrapped method */ public AMQCommand(com.rabbitmq.client.Method method) { - this(method, null, null); + this(method, null, null, Integer.MAX_VALUE); } /** @@ -64,7 +68,19 @@ public AMQCommand(com.rabbitmq.client.Method method) { * @param body the message body data */ public AMQCommand(com.rabbitmq.client.Method method, AMQContentHeader contentHeader, byte[] body) { - this.assembler = new CommandAssembler((Method) method, contentHeader, body); + this.assembler = new CommandAssembler((Method) method, contentHeader, body, Integer.MAX_VALUE); + } + + /** + * Construct a command with a specified method, header and body. + * @param method the wrapped method + * @param contentHeader the wrapped content header + * @param body the message body data + * @param maxBodyLength the maximum size for an inbound message body + */ + public AMQCommand(com.rabbitmq.client.Method method, AMQContentHeader contentHeader, byte[] body, + int maxBodyLength) { + this.assembler = new CommandAssembler((Method) method, contentHeader, body, maxBodyLength); } /** Public API - {@inheritDoc} */ diff --git a/src/main/java/com/rabbitmq/client/impl/AMQConnection.java b/src/main/java/com/rabbitmq/client/impl/AMQConnection.java index 2592345baa..fd1d4531b8 100644 --- a/src/main/java/com/rabbitmq/client/impl/AMQConnection.java +++ b/src/main/java/com/rabbitmq/client/impl/AMQConnection.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -157,6 +157,7 @@ public static Map defaultClientProperties() { private volatile ChannelManager _channelManager; /** Saved server properties field from connection.start */ private volatile Map _serverProperties; + private final int maxInboundMessageBodySize; /** * Protected API - respond, in the driver thread, to a ShutdownSignal. @@ -244,6 +245,7 @@ public AMQConnection(ConnectionParams params, FrameHandler frameHandler, Metrics this.credentialsRefreshService = params.getCredentialsRefreshService(); + this._channel0 = createChannel0(); this._channelManager = null; @@ -257,6 +259,7 @@ public AMQConnection(ConnectionParams params, FrameHandler frameHandler, Metrics this.errorOnWriteListener = params.getErrorOnWriteListener() != null ? params.getErrorOnWriteListener() : (connection, exception) -> { throw exception; }; // we just propagate the exception for non-recoverable connections this.workPoolTimeout = params.getWorkPoolTimeout(); + this.maxInboundMessageBodySize = params.getMaxInboundMessageBodySize(); } AMQChannel createChannel0() { @@ -605,7 +608,9 @@ public Channel createChannel(int channelNumber) throws IOException { ChannelManager cm = _channelManager; if (cm == null) return null; Channel channel = cm.createChannel(this, channelNumber); - metricsCollector.newChannel(channel); + if (channel != null) { + metricsCollector.newChannel(channel); + } return channel; } @@ -616,7 +621,9 @@ public Channel createChannel() throws IOException { ChannelManager cm = _channelManager; if (cm == null) return null; Channel channel = cm.createChannel(this); - metricsCollector.newChannel(channel); + if (channel != null) { + metricsCollector.newChannel(channel); + } return channel; } @@ -750,8 +757,8 @@ private void readFrame(Frame frame) throws IOException { /** private API */ public void handleHeartbeatFailure() { - Exception ex = new MissedHeartbeatException("Heartbeat missing with heartbeat = " + - _heartbeat + " seconds"); + Exception ex = new MissedHeartbeatException("Detected missed server heartbeats, heartbeat interval: " + + _heartbeat + " seconds, RabbitMQ node hostname: " + this.getHostAddress()); try { _exceptionHandler.handleUnexpectedConnectionDriverException(this, ex); shutdown(null, false, ex, true); @@ -1198,4 +1205,8 @@ public boolean willCheckRpcResponseType() { public TrafficListener getTrafficListener() { return trafficListener; } + + int getMaxInboundMessageBodySize() { + return maxInboundMessageBodySize; + } } diff --git a/src/main/java/com/rabbitmq/client/impl/AbstractFrameHandlerFactory.java b/src/main/java/com/rabbitmq/client/impl/AbstractFrameHandlerFactory.java index 32eb46712f..61f4c51325 100644 --- a/src/main/java/com/rabbitmq/client/impl/AbstractFrameHandlerFactory.java +++ b/src/main/java/com/rabbitmq/client/impl/AbstractFrameHandlerFactory.java @@ -1,3 +1,18 @@ +// Copyright (c) 2016-2023 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + package com.rabbitmq.client.impl; import com.rabbitmq.client.SocketConfigurator; @@ -10,10 +25,13 @@ public abstract class AbstractFrameHandlerFactory implements FrameHandlerFactory protected final int connectionTimeout; protected final SocketConfigurator configurator; protected final boolean ssl; + protected final int maxInboundMessageBodySize; - protected AbstractFrameHandlerFactory(int connectionTimeout, SocketConfigurator configurator, boolean ssl) { + protected AbstractFrameHandlerFactory(int connectionTimeout, SocketConfigurator configurator, + boolean ssl, int maxInboundMessageBodySize) { this.connectionTimeout = connectionTimeout; this.configurator = configurator; this.ssl = ssl; + this.maxInboundMessageBodySize = maxInboundMessageBodySize; } } diff --git a/src/main/java/com/rabbitmq/client/impl/AbstractMetricsCollector.java b/src/main/java/com/rabbitmq/client/impl/AbstractMetricsCollector.java index 44cf1aff9e..7ece72ad4c 100644 --- a/src/main/java/com/rabbitmq/client/impl/AbstractMetricsCollector.java +++ b/src/main/java/com/rabbitmq/client/impl/AbstractMetricsCollector.java @@ -72,12 +72,14 @@ public void closeConnection(Connection connection) { @Override public void newChannel(final Channel channel) { - try { - incrementChannelCount(channel); - channel.addShutdownListener(cause -> closeChannel(channel)); - connectionState(channel.getConnection()).channelState.put(channel.getChannelNumber(), new ChannelState(channel)); - } catch(Exception e) { - LOGGER.info("Error while computing metrics in newChannel: " + e.getMessage()); + if (channel != null) { + try { + incrementChannelCount(channel); + channel.addShutdownListener(cause -> closeChannel(channel)); + connectionState(channel.getConnection()).channelState.put(channel.getChannelNumber(), new ChannelState(channel)); + } catch(Exception e) { + LOGGER.info("Error while computing metrics in newChannel: " + e.getMessage()); + } } } diff --git a/src/main/java/com/rabbitmq/client/impl/ChannelManager.java b/src/main/java/com/rabbitmq/client/impl/ChannelManager.java index 59f7bb3fee..fb0490eade 100644 --- a/src/main/java/com/rabbitmq/client/impl/ChannelManager.java +++ b/src/main/java/com/rabbitmq/client/impl/ChannelManager.java @@ -39,9 +39,9 @@ public class ChannelManager { /** Monitor for _channelMap and channelNumberAllocator */ private final Object monitor = new Object(); - /** Mapping from 1.._channelMax to {@link ChannelN} instance */ - private final Map _channelMap = new HashMap(); - private final IntAllocator channelNumberAllocator; + /** Mapping from 1.._channelMax to {@link ChannelN} instance */ + private final Map _channelMap = new HashMap(); + private final IntAllocator channelNumberAllocator; private final ConsumerWorkService workService; @@ -70,6 +70,8 @@ public ChannelManager(ConsumerWorkService workService, int channelMax, ThreadFac public ChannelManager(ConsumerWorkService workService, int channelMax, ThreadFactory threadFactory, MetricsCollector metricsCollector) { + if (channelMax < 0) + throw new IllegalArgumentException("create ChannelManager: 'channelMax' must be greater or equal to 0."); if (channelMax == 0) { // The framing encoding only allows for unsigned 16-bit integers // for the channel number diff --git a/src/main/java/com/rabbitmq/client/impl/ChannelN.java b/src/main/java/com/rabbitmq/client/impl/ChannelN.java index 8a769a0d45..3c97d339e8 100644 --- a/src/main/java/com/rabbitmq/client/impl/ChannelN.java +++ b/src/main/java/com/rabbitmq/client/impl/ChannelN.java @@ -708,7 +708,7 @@ public void basicPublish(String exchange, String routingKey, .build(), props, body); try { transmit(command); - } catch (IOException e) { + } catch (IOException | AlreadyClosedException e) { metricsCollector.basicPublishFailure(this, e); throw e; } @@ -1489,7 +1489,7 @@ public Consumer transformReply(AMQCommand replyCommand) { rpc(m, k); - + try { if(_rpcTimeout == NO_RPC_TIMEOUT) { k.getReply(); // discard result diff --git a/src/main/java/com/rabbitmq/client/impl/CommandAssembler.java b/src/main/java/com/rabbitmq/client/impl/CommandAssembler.java index f19294862f..2ff9f10e3d 100644 --- a/src/main/java/com/rabbitmq/client/impl/CommandAssembler.java +++ b/src/main/java/com/rabbitmq/client/impl/CommandAssembler.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -21,6 +21,7 @@ import com.rabbitmq.client.AMQP; import com.rabbitmq.client.UnexpectedFrameError; +import static java.lang.String.format; /** * Class responsible for piecing together a command from a series of {@link Frame}s. @@ -52,12 +53,16 @@ private enum CAState { /** No bytes of content body not yet accumulated */ private long remainingBodyBytes; - public CommandAssembler(Method method, AMQContentHeader contentHeader, byte[] body) { + private final int maxBodyLength; + + public CommandAssembler(Method method, AMQContentHeader contentHeader, byte[] body, + int maxBodyLength) { this.method = method; this.contentHeader = contentHeader; - this.bodyN = new ArrayList(2); + this.bodyN = new ArrayList<>(2); this.bodyLength = 0; this.remainingBodyBytes = 0; + this.maxBodyLength = maxBodyLength; appendBodyFragment(body); if (method == null) { this.state = CAState.EXPECTING_METHOD; @@ -99,7 +104,16 @@ private void consumeMethodFrame(Frame f) throws IOException { private void consumeHeaderFrame(Frame f) throws IOException { if (f.type == AMQP.FRAME_HEADER) { this.contentHeader = AMQImpl.readContentHeaderFrom(f.getInputStream()); - this.remainingBodyBytes = this.contentHeader.getBodySize(); + long bodySize = this.contentHeader.getBodySize(); + if (bodySize >= this.maxBodyLength) { + throw new IllegalStateException(format( + "Message body is too large (%d), maximum configured size is %d. " + + "See ConnectionFactory#setMaxInboundMessageBodySize " + + "if you need to increase the limit.", + bodySize, this.maxBodyLength + )); + } + this.remainingBodyBytes = bodySize; updateContentBodyState(); } else { throw new UnexpectedFrameError(f, AMQP.FRAME_HEADER); diff --git a/src/main/java/com/rabbitmq/client/impl/ConnectionParams.java b/src/main/java/com/rabbitmq/client/impl/ConnectionParams.java index 24d20040ef..9fe6e8558d 100644 --- a/src/main/java/com/rabbitmq/client/impl/ConnectionParams.java +++ b/src/main/java/com/rabbitmq/client/impl/ConnectionParams.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -64,6 +64,8 @@ public class ConnectionParams { private CredentialsRefreshService credentialsRefreshService; + private int maxInboundMessageBodySize; + public ConnectionParams() {} public CredentialsProvider getCredentialsProvider() { @@ -297,4 +299,12 @@ public void setCredentialsRefreshService(CredentialsRefreshService credentialsRe public CredentialsRefreshService getCredentialsRefreshService() { return credentialsRefreshService; } + + public int getMaxInboundMessageBodySize() { + return maxInboundMessageBodySize; + } + + public void setMaxInboundMessageBodySize(int maxInboundMessageBodySize) { + this.maxInboundMessageBodySize = maxInboundMessageBodySize; + } } diff --git a/src/main/java/com/rabbitmq/client/impl/ConsumerWorkService.java b/src/main/java/com/rabbitmq/client/impl/ConsumerWorkService.java index b3810aae2f..656f68cae7 100644 --- a/src/main/java/com/rabbitmq/client/impl/ConsumerWorkService.java +++ b/src/main/java/com/rabbitmq/client/impl/ConsumerWorkService.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2022 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -22,10 +22,13 @@ import java.util.concurrent.ThreadFactory; import com.rabbitmq.client.Channel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; final public class ConsumerWorkService { - private static final int MAX_RUNNABLE_BLOCK_SIZE = 16; - private static final int DEFAULT_NUM_THREADS = Runtime.getRuntime().availableProcessors() * 2; + private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerWorkService.class); + private static final int MAX_RUNNABLE_BLOCK_SIZE = 256; + private static final int DEFAULT_NUM_THREADS = Math.max(1, Utils.availableProcessors()); private final ExecutorService executor; private final boolean privateExecutor; private final WorkPool workPool; @@ -33,8 +36,12 @@ final public class ConsumerWorkService { public ConsumerWorkService(ExecutorService executor, ThreadFactory threadFactory, int queueingTimeout, int shutdownTimeout) { this.privateExecutor = (executor == null); - this.executor = (executor == null) ? Executors.newFixedThreadPool(DEFAULT_NUM_THREADS, threadFactory) - : executor; + if (executor == null) { + LOGGER.debug("Creating executor service with {} thread(s) for consumer work service", DEFAULT_NUM_THREADS); + this.executor = Executors.newFixedThreadPool(DEFAULT_NUM_THREADS, threadFactory); + } else { + this.executor = executor; + } this.workPool = new WorkPool<>(queueingTimeout); this.shutdownTimeout = shutdownTimeout; } diff --git a/src/main/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshService.java b/src/main/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshService.java index f4edeae391..4f5968fcc9 100644 --- a/src/main/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshService.java +++ b/src/main/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshService.java @@ -34,7 +34,7 @@ *

* This implementation keeps track of entities (typically AMQP connections) that need * to renew credentials. Token renewal is scheduled based on token expiration, using - * a Function refreshDelayStrategy. Once credentials + * a Function<Duration, Long> refreshDelayStrategy. Once credentials * for a {@link CredentialsProvider} have been renewed, the callback registered * by each entity/connection is performed. This callback typically propagates * the new credentials in the entity state, e.g. sending the new password to the @@ -140,7 +140,7 @@ public static Function fixedDelayBeforeExpirationRefreshDela } /** - * Advise to refresh credentials if TTL <= limit. + * Advise to refresh credentials if TTL <= limit. * * @param limitBeforeExpiration * @return true if credentials should be refreshed, false otherwise diff --git a/src/main/java/com/rabbitmq/client/impl/Environment.java b/src/main/java/com/rabbitmq/client/impl/Environment.java index 149b9a102e..2676311322 100644 --- a/src/main/java/com/rabbitmq/client/impl/Environment.java +++ b/src/main/java/com/rabbitmq/client/impl/Environment.java @@ -23,32 +23,29 @@ * Package-protected API. */ public class Environment { + + /** + * This method is deprecated and subject to removal in the next major release. + * + * There is no replacement for this method, as it used to use the + * {@link SecurityManager}, which is itself deprecated and subject to removal. + * @deprecated + * @return always returns true + */ + @Deprecated public static boolean isAllowedToModifyThreads() { - try { - SecurityManager sm = System.getSecurityManager(); - if(sm != null) { - sm.checkPermission(new RuntimePermission("modifyThread")); - sm.checkPermission(new RuntimePermission("modifyThreadGroup")); - } - return true; - } catch (SecurityException se) { - return false; - } + return true; } public static Thread newThread(ThreadFactory factory, Runnable runnable, String name) { Thread t = factory.newThread(runnable); - if(isAllowedToModifyThreads()) { - t.setName(name); - } + t.setName(name); return t; } public static Thread newThread(ThreadFactory factory, Runnable runnable, String name, boolean isDaemon) { Thread t = newThread(factory, runnable, name); - if(isAllowedToModifyThreads()) { - t.setDaemon(isDaemon); - } + t.setDaemon(isDaemon); return t; } } diff --git a/src/main/java/com/rabbitmq/client/impl/Frame.java b/src/main/java/com/rabbitmq/client/impl/Frame.java index b1ecd916dd..d1332b79d0 100644 --- a/src/main/java/com/rabbitmq/client/impl/Frame.java +++ b/src/main/java/com/rabbitmq/client/impl/Frame.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -22,10 +22,10 @@ import java.io.*; import java.math.BigDecimal; import java.net.SocketTimeoutException; -import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.Map; +import static java.lang.String.format; /** * Represents an AMQP wire-protocol frame, with frame type, channel number, and payload bytes. @@ -83,7 +83,7 @@ public static Frame fromBodyFragment(int channelNumber, byte[] body, int offset, * * @return a new Frame if we read a frame successfully, otherwise null */ - public static Frame readFrom(DataInputStream is) throws IOException { + public static Frame readFrom(DataInputStream is, int maxPayloadSize) throws IOException { int type; int channel; @@ -109,6 +109,14 @@ public static Frame readFrom(DataInputStream is) throws IOException { channel = is.readUnsignedShort(); int payloadSize = is.readInt(); + if (payloadSize >= maxPayloadSize) { + throw new IllegalStateException(format( + "Frame body is too large (%d), maximum configured size is %d. " + + "See ConnectionFactory#setMaxInboundMessageBodySize " + + "if you need to increase the limit.", + payloadSize, maxPayloadSize + )); + } byte[] payload = new byte[payloadSize]; is.readFully(payload); @@ -269,7 +277,7 @@ else if(value instanceof Integer) { else if(value instanceof BigDecimal) { acc += 5; } - else if(value instanceof Date || value instanceof Timestamp) { + else if(value instanceof Date) { acc += 8; } else if(value instanceof Map) { diff --git a/src/main/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProvider.java b/src/main/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProvider.java index 5e9618317d..65cd9ef2da 100644 --- a/src/main/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProvider.java +++ b/src/main/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProvider.java @@ -18,6 +18,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.rabbitmq.client.TrustEverythingTrustManager; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; @@ -72,7 +74,7 @@ public class OAuth2ClientCredentialsGrantCredentialsProvider extends RefreshProt private final Map parameters; - private final ObjectMapper objectMapper = new ObjectMapper(); + private final AtomicReference> tokenExtractor = new AtomicReference<>(); private final String id; @@ -214,14 +216,8 @@ protected String usernameFromToken(Token token) { } protected Token parseToken(String response) { - try { - Map map = objectMapper.readValue(response, Map.class); - int expiresIn = ((Number) map.get("expires_in")).intValue(); - Instant receivedAt = Instant.now(); - return new Token(map.get("access_token").toString(), expiresIn, receivedAt); - } catch (IOException e) { - throw new OAuthTokenManagementException("Error while parsing OAuth 2 token", e); - } + return this.tokenExtractor.updateAndGet(current -> + current == null ? new JacksonTokenLookup() : current).apply(response); } @Override @@ -595,5 +591,21 @@ private SSLSocketFactory sslSocketFactory() { } } + + private static class JacksonTokenLookup implements Function { + + private final ObjectMapper objectMapper = new ObjectMapper(); + @Override + public Token apply(String response) { + try { + Map map = objectMapper.readValue(response, Map.class); + int expiresIn = ((Number) map.get("expires_in")).intValue(); + Instant receivedAt = Instant.now(); + return new Token(map.get("access_token").toString(), expiresIn, receivedAt); + } catch (IOException e) { + throw new OAuthTokenManagementException("Error while parsing OAuth 2 token", e); + } + } + } } \ No newline at end of file diff --git a/src/main/java/com/rabbitmq/client/impl/OpenTelemetryMetricsCollector.java b/src/main/java/com/rabbitmq/client/impl/OpenTelemetryMetricsCollector.java new file mode 100644 index 0000000000..685865d5a6 --- /dev/null +++ b/src/main/java/com/rabbitmq/client/impl/OpenTelemetryMetricsCollector.java @@ -0,0 +1,195 @@ +// Copyright (c) 2022 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client.impl; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.MetricsCollector; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * OpenTelemetry implementation of {@link MetricsCollector}. + * + * @see MetricsCollector + * @since 5.16.0 + */ +public class OpenTelemetryMetricsCollector extends AbstractMetricsCollector { + + private final Attributes attributes; + + private final AtomicLong connections = new AtomicLong(0L); + private final AtomicLong channels = new AtomicLong(0L); + + private final LongCounter publishedMessagesCounter; + private final LongCounter consumedMessagesCounter; + private final LongCounter acknowledgedMessagesCounter; + private final LongCounter rejectedMessagesCounter; + private final LongCounter failedToPublishMessagesCounter; + private final LongCounter ackedPublishedMessagesCounter; + private final LongCounter nackedPublishedMessagesCounter; + private final LongCounter unroutedPublishedMessagesCounter; + + public OpenTelemetryMetricsCollector(OpenTelemetry openTelemetry) { + this(openTelemetry, "rabbitmq"); + } + + public OpenTelemetryMetricsCollector(final OpenTelemetry openTelemetry, final String prefix) { + this(openTelemetry, prefix, Attributes.empty()); + } + + public OpenTelemetryMetricsCollector(final OpenTelemetry openTelemetry, final String prefix, final Attributes attributes) { + // initialize meter + Meter meter = openTelemetry.getMeter("amqp-client"); + + // attributes + this.attributes = attributes; + + // connections + meter.gaugeBuilder(prefix + ".connections") + .setUnit("{connections}") + .setDescription("The number of connections to the RabbitMQ server") + .ofLongs() + .buildWithCallback(measurement -> measurement.record(connections.get(), attributes)); + + // channels + meter.gaugeBuilder(prefix + ".channels") + .setUnit("{channels}") + .setDescription("The number of channels to the RabbitMQ server") + .ofLongs() + .buildWithCallback(measurement -> measurement.record(channels.get(), attributes)); + + // publishedMessages + this.publishedMessagesCounter = meter.counterBuilder(prefix + ".published") + .setUnit("{messages}") + .setDescription("The number of messages published to the RabbitMQ server") + .build(); + + // consumedMessages + this.consumedMessagesCounter = meter.counterBuilder(prefix + ".consumed") + .setUnit("{messages}") + .setDescription("The number of messages consumed from the RabbitMQ server") + .build(); + + // acknowledgedMessages + this.acknowledgedMessagesCounter = meter.counterBuilder(prefix + ".acknowledged") + .setUnit("{messages}") + .setDescription("The number of messages acknowledged from the RabbitMQ server") + .build(); + + // rejectedMessages + this.rejectedMessagesCounter = meter.counterBuilder(prefix + ".rejected") + .setUnit("{messages}") + .setDescription("The number of messages rejected from the RabbitMQ server") + .build(); + + // failedToPublishMessages + this.failedToPublishMessagesCounter = meter.counterBuilder(prefix + ".failed_to_publish") + .setUnit("{messages}") + .setDescription("The number of messages failed to publish to the RabbitMQ server") + .build(); + + // ackedPublishedMessages + this.ackedPublishedMessagesCounter = meter.counterBuilder(prefix + ".acknowledged_published") + .setUnit("{messages}") + .setDescription("The number of published messages acknowledged by the RabbitMQ server") + .build(); + + // nackedPublishedMessages + this.nackedPublishedMessagesCounter = meter.counterBuilder(prefix + ".not_acknowledged_published") + .setUnit("{messages}") + .setDescription("The number of published messages not acknowledged by the RabbitMQ server") + .build(); + + // unroutedPublishedMessages + this.unroutedPublishedMessagesCounter = meter.counterBuilder(prefix + ".unrouted_published") + .setUnit("{messages}") + .setDescription("The number of un-routed published messages to the RabbitMQ server") + .build(); + } + + @Override + protected void incrementConnectionCount(Connection connection) { + connections.incrementAndGet(); + } + + @Override + protected void decrementConnectionCount(Connection connection) { + connections.decrementAndGet(); + } + + @Override + protected void incrementChannelCount(Channel channel) { + channels.incrementAndGet(); + } + + @Override + protected void decrementChannelCount(Channel channel) { + channels.decrementAndGet(); + } + + @Override + protected void markPublishedMessage() { + publishedMessagesCounter.add(1L, attributes); + } + + @Override + protected void markMessagePublishFailed() { + failedToPublishMessagesCounter.add(1L, attributes); + } + + @Override + protected void markConsumedMessage() { + consumedMessagesCounter.add(1L, attributes); + } + + @Override + protected void markAcknowledgedMessage() { + acknowledgedMessagesCounter.add(1L, attributes); + } + + @Override + protected void markRejectedMessage() { + rejectedMessagesCounter.add(1L, attributes); + } + + @Override + protected void markMessagePublishAcknowledged() { + ackedPublishedMessagesCounter.add(1L, attributes); + } + + @Override + protected void markMessagePublishNotAcknowledged() { + nackedPublishedMessagesCounter.add(1L, attributes); + } + + @Override + protected void markPublishedMessageUnrouted() { + unroutedPublishedMessagesCounter.add(1L, attributes); + } + + public AtomicLong getConnections() { + return connections; + } + + public AtomicLong getChannels() { + return channels; + } +} diff --git a/src/main/java/com/rabbitmq/client/impl/SocketFrameHandler.java b/src/main/java/com/rabbitmq/client/impl/SocketFrameHandler.java index 6efd6f83f9..5048100a7b 100644 --- a/src/main/java/com/rabbitmq/client/impl/SocketFrameHandler.java +++ b/src/main/java/com/rabbitmq/client/impl/SocketFrameHandler.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -52,6 +52,8 @@ public class SocketFrameHandler implements FrameHandler { /** Socket's outputstream - data to the broker - synchronized on */ private final DataOutputStream _outputStream; + private final int maxInboundMessageBodySize; + /** Time to linger before closing the socket forcefully. */ public static final int SOCKET_CLOSING_TIMEOUT = 1; @@ -59,15 +61,17 @@ public class SocketFrameHandler implements FrameHandler { * @param socket the socket to use */ public SocketFrameHandler(Socket socket) throws IOException { - this(socket, null); + this(socket, null, Integer.MAX_VALUE); } /** * @param socket the socket to use */ - public SocketFrameHandler(Socket socket, ExecutorService shutdownExecutor) throws IOException { + public SocketFrameHandler(Socket socket, ExecutorService shutdownExecutor, + int maxInboundMessageBodySize) throws IOException { _socket = socket; _shutdownExecutor = shutdownExecutor; + this.maxInboundMessageBodySize = maxInboundMessageBodySize; _inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream())); _outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); @@ -181,7 +185,7 @@ public void initialize(AMQConnection connection) { @Override public Frame readFrame() throws IOException { synchronized (_inputStream) { - return Frame.readFrom(_inputStream); + return Frame.readFrom(_inputStream, this.maxInboundMessageBodySize); } } diff --git a/src/main/java/com/rabbitmq/client/impl/SocketFrameHandlerFactory.java b/src/main/java/com/rabbitmq/client/impl/SocketFrameHandlerFactory.java index 1186b6ea93..40818c46ba 100644 --- a/src/main/java/com/rabbitmq/client/impl/SocketFrameHandlerFactory.java +++ b/src/main/java/com/rabbitmq/client/impl/SocketFrameHandlerFactory.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -22,7 +22,6 @@ import javax.net.SocketFactory; import java.io.IOException; -import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.ExecutorService; @@ -39,26 +38,27 @@ public SocketFrameHandlerFactory(int connectionTimeout, SocketFactory socketFact public SocketFrameHandlerFactory(int connectionTimeout, SocketFactory socketFactory, SocketConfigurator configurator, boolean ssl, ExecutorService shutdownExecutor) { - this(connectionTimeout, socketFactory, configurator, ssl, shutdownExecutor, null); + this(connectionTimeout, socketFactory, configurator, ssl, shutdownExecutor, null, + Integer.MAX_VALUE); } public SocketFrameHandlerFactory(int connectionTimeout, SocketFactory socketFactory, SocketConfigurator configurator, - boolean ssl, ExecutorService shutdownExecutor, SslContextFactory sslContextFactory) { - super(connectionTimeout, configurator, ssl); + boolean ssl, ExecutorService shutdownExecutor, SslContextFactory sslContextFactory, + int maxInboundMessageBodySize) { + super(connectionTimeout, configurator, ssl, maxInboundMessageBodySize); this.socketFactory = socketFactory; this.shutdownExecutor = shutdownExecutor; this.sslContextFactory = sslContextFactory; } public FrameHandler create(Address addr, String connectionName) throws IOException { - String hostName = addr.getHost(); int portNumber = ConnectionFactory.portOrDefault(addr.getPort(), ssl); Socket socket = null; try { socket = createSocket(connectionName); configurator.configure(socket); - socket.connect(new InetSocketAddress(hostName, portNumber), - connectionTimeout); + + socket.connect(addr.toInetSocketAddress(portNumber), connectionTimeout); return create(socket); } catch (IOException ioe) { quietTrySocketClose(socket); @@ -81,7 +81,7 @@ protected Socket createSocket(String connectionName) throws IOException { public FrameHandler create(Socket sock) throws IOException { - return new SocketFrameHandler(sock, this.shutdownExecutor); + return new SocketFrameHandler(sock, this.shutdownExecutor, this.maxInboundMessageBodySize); } private static void quietTrySocketClose(Socket socket) { diff --git a/src/main/java/com/rabbitmq/client/impl/TlsUtils.java b/src/main/java/com/rabbitmq/client/impl/TlsUtils.java index a11deddc2c..aa103607ec 100644 --- a/src/main/java/com/rabbitmq/client/impl/TlsUtils.java +++ b/src/main/java/com/rabbitmq/client/impl/TlsUtils.java @@ -104,7 +104,7 @@ public static String peerCertificateInfo(Certificate certificate, String prefix) try { return String.format("%s subject: %s, subject alternative names: %s, " + "issuer: %s, not valid after: %s, X.509 usage extensions: %s", - stripCRLF(prefix), stripCRLF(c.getSubjectDN().getName()), stripCRLF(sans(c, ",")), stripCRLF(c.getIssuerDN().getName()), + stripCRLF(prefix), stripCRLF(c.getSubjectX500Principal().getName()), stripCRLF(sans(c, ",")), stripCRLF(c.getIssuerX500Principal().getName()), c.getNotAfter(), stripCRLF(extensions(c))); } catch (Exception e) { return "Error while retrieving " + prefix + " certificate information"; diff --git a/src/main/java/com/rabbitmq/client/impl/Utils.java b/src/main/java/com/rabbitmq/client/impl/Utils.java new file mode 100644 index 0000000000..d3e3412ee4 --- /dev/null +++ b/src/main/java/com/rabbitmq/client/impl/Utils.java @@ -0,0 +1,31 @@ +// Copyright (c) 2022 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client.impl; + +final class Utils { + + private static final int AVAILABLE_PROCESSORS = + Integer.parseInt( + System.getProperty( + "rabbitmq.amqp.client.availableProcessors", + String.valueOf(Runtime.getRuntime().availableProcessors()))); + + static int availableProcessors() { + return AVAILABLE_PROCESSORS; + } + + private Utils() {} +} diff --git a/src/main/java/com/rabbitmq/client/impl/ValueReader.java b/src/main/java/com/rabbitmq/client/impl/ValueReader.java index 1162cc8af0..ed7f41284c 100644 --- a/src/main/java/com/rabbitmq/client/impl/ValueReader.java +++ b/src/main/java/com/rabbitmq/client/impl/ValueReader.java @@ -186,6 +186,9 @@ static Object readFieldValue(DataInputStream in) case 'b': value = in.readByte(); break; + case 'B': + value = in.readUnsignedByte(); + break; case 'd': value = in.readDouble(); break; diff --git a/src/main/java/com/rabbitmq/client/impl/nio/FrameBuilder.java b/src/main/java/com/rabbitmq/client/impl/nio/FrameBuilder.java index 8352174360..3562e92a1b 100644 --- a/src/main/java/com/rabbitmq/client/impl/nio/FrameBuilder.java +++ b/src/main/java/com/rabbitmq/client/impl/nio/FrameBuilder.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -23,6 +23,7 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; +import static java.lang.String.format; /** * Class to create AMQP frames from a {@link ReadableByteChannel}. @@ -43,6 +44,7 @@ public class FrameBuilder { protected final ReadableByteChannel channel; protected final ByteBuffer applicationBuffer; + private final int maxPayloadSize; // to store the bytes of the outstanding data // 3 byte-long because the longest we read is an unsigned int // (not need to store the latest byte) @@ -52,9 +54,10 @@ public class FrameBuilder { private byte[] framePayload; private int bytesRead = 0; - public FrameBuilder(ReadableByteChannel channel, ByteBuffer buffer) { + public FrameBuilder(ReadableByteChannel channel, ByteBuffer buffer, int maxPayloadSize) { this.channel = channel; this.applicationBuffer = buffer; + this.maxPayloadSize = maxPayloadSize; } /** @@ -65,7 +68,7 @@ public FrameBuilder(ReadableByteChannel channel, ByteBuffer buffer) { * * @return a complete frame or null if a frame couldn't have been fully built * @throws IOException - * @see Frame#readFrom(DataInputStream) + * @see Frame#readFrom(DataInputStream, int) */ public Frame readFrame() throws IOException { while (somethingToRead()) { @@ -93,6 +96,14 @@ public Frame readFrame() throws IOException { } else if (bytesRead == 6) { // payload size 4/4 int framePayloadSize = (frameBuffer[0] << 24) + (frameBuffer[1] << 16) + (frameBuffer[2] << 8) + readFromBuffer(); + if (framePayloadSize >= maxPayloadSize) { + throw new IllegalStateException(format( + "Frame body is too large (%d), maximum configured size is %d. " + + "See ConnectionFactory#setMaxInboundMessageBodySize " + + "if you need to increase the limit.", + framePayloadSize, maxPayloadSize + )); + } framePayload = new byte[framePayloadSize]; } else if (bytesRead >= PAYLOAD_OFFSET && bytesRead < framePayload.length + PAYLOAD_OFFSET) { framePayload[bytesRead - PAYLOAD_OFFSET] = (byte) readFromBuffer(); @@ -200,4 +211,9 @@ private void handleProtocolVersionMismatch() throws IOException { } throw x; } + + //Indicates ssl underflow state - means that cipherBuffer should aggregate next chunks of bytes + public boolean isUnderflowHandlingEnabled() { + return false; + } } diff --git a/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerFactory.java b/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerFactory.java index 10f550d70a..ed0a4f20f8 100644 --- a/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerFactory.java +++ b/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerFactory.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -21,6 +21,9 @@ import com.rabbitmq.client.impl.AbstractFrameHandlerFactory; import com.rabbitmq.client.impl.FrameHandler; import com.rabbitmq.client.impl.TlsUtils; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,12 +58,13 @@ public class SocketChannelFrameHandlerFactory extends AbstractFrameHandlerFactor private final List nioLoopContexts; - public SocketChannelFrameHandlerFactory(int connectionTimeout, NioParams nioParams, boolean ssl, SslContextFactory sslContextFactory) - throws IOException { - super(connectionTimeout, null, ssl); + public SocketChannelFrameHandlerFactory(int connectionTimeout, NioParams nioParams, boolean ssl, + SslContextFactory sslContextFactory, + int maxInboundMessageBodySize) { + super(connectionTimeout, null, ssl, maxInboundMessageBodySize); this.nioParams = new NioParams(nioParams); this.sslContextFactory = sslContextFactory; - this.nioLoopContexts = new ArrayList(this.nioParams.getNbIoThreads()); + this.nioLoopContexts = new ArrayList<>(this.nioParams.getNbIoThreads()); for (int i = 0; i < this.nioParams.getNbIoThreads(); i++) { this.nioLoopContexts.add(new NioLoopContext(this, this.nioParams)); } @@ -83,7 +87,7 @@ public FrameHandler create(Address addr, String connectionName) throws IOExcepti } } - SocketAddress address = new InetSocketAddress(addr.getHost(), portNumber); + SocketAddress address = addr.toInetSocketAddress(portNumber); // No Sonar: the channel is closed in case of error and it cannot // be closed here because it's part of the state of the connection // to be returned. @@ -93,16 +97,25 @@ public FrameHandler create(Address addr, String connectionName) throws IOExcepti nioParams.getSocketChannelConfigurator().configure(channel); } - channel.connect(address); + channel.socket().connect(address, this.connectionTimeout); + if (ssl) { + int initialSoTimeout = channel.socket().getSoTimeout(); + channel.socket().setSoTimeout(this.connectionTimeout); sslEngine.beginHandshake(); try { - boolean handshake = SslEngineHelper.doHandshake(channel, sslEngine); + ReadableByteChannel wrappedReadChannel = Channels.newChannel( + channel.socket().getInputStream()); + WritableByteChannel wrappedWriteChannel = Channels.newChannel( + channel.socket().getOutputStream()); + boolean handshake = SslEngineHelper.doHandshake( + wrappedWriteChannel, wrappedReadChannel, sslEngine); if (!handshake) { LOGGER.error("TLS connection failed"); throw new SSLException("TLS handshake failed"); } + channel.socket().setSoTimeout(initialSoTimeout); } catch (SSLHandshakeException e) { LOGGER.error("TLS connection failed: {}", e.getMessage()); throw e; @@ -123,7 +136,8 @@ public FrameHandler create(Address addr, String connectionName) throws IOExcepti channel, nioLoopContext, nioParams, - sslEngine + sslEngine, + this.maxInboundMessageBodySize ); state.startReading(); SocketChannelFrameHandler frameHandler = new SocketChannelFrameHandler(state); diff --git a/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerState.java b/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerState.java index 50f08a59f2..b1a391fd65 100644 --- a/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerState.java +++ b/src/main/java/com/rabbitmq/client/impl/nio/SocketChannelFrameHandlerState.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -27,6 +27,7 @@ import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; + /** * */ @@ -70,7 +71,9 @@ public class SocketChannelFrameHandlerState { final FrameBuilder frameBuilder; - public SocketChannelFrameHandlerState(SocketChannel channel, NioLoopContext nioLoopsState, NioParams nioParams, SSLEngine sslEngine) { + public SocketChannelFrameHandlerState(SocketChannel channel, NioLoopContext nioLoopsState, + NioParams nioParams, SSLEngine sslEngine, + int maxFramePayloadSize) { this.channel = channel; this.readSelectorState = nioLoopsState.readSelectorState; this.writeSelectorState = nioLoopsState.writeSelectorState; @@ -93,7 +96,7 @@ public SocketChannelFrameHandlerState(SocketChannel channel, NioLoopContext nioL new ByteBufferOutputStream(channel, plainOut) ); - this.frameBuilder = new FrameBuilder(channel, plainIn); + this.frameBuilder = new FrameBuilder(channel, plainIn, maxFramePayloadSize); } else { this.ssl = true; @@ -105,7 +108,8 @@ public SocketChannelFrameHandlerState(SocketChannel channel, NioLoopContext nioL this.outputStream = new DataOutputStream( new SslEngineByteBufferOutputStream(sslEngine, plainOut, cipherOut, channel) ); - this.frameBuilder = new SslEngineFrameBuilder(sslEngine, plainIn, cipherIn, channel); + this.frameBuilder = new SslEngineFrameBuilder(sslEngine, plainIn, + cipherIn, channel, maxFramePayloadSize); } } @@ -176,11 +180,14 @@ void endWriteSequence() { void prepareForReadSequence() throws IOException { if(ssl) { - cipherIn.clear(); - plainIn.clear(); + if (!frameBuilder.isUnderflowHandlingEnabled()) { + cipherIn.clear(); + cipherIn.flip(); + } - cipherIn.flip(); + plainIn.clear(); plainIn.flip(); + } else { NioHelper.read(channel, plainIn); plainIn.flip(); @@ -189,6 +196,15 @@ void prepareForReadSequence() throws IOException { boolean continueReading() throws IOException { if(ssl) { + if (frameBuilder.isUnderflowHandlingEnabled()) { + int bytesRead = NioHelper.read(channel, cipherIn); + if (bytesRead == 0) { + return false; + } else { + cipherIn.flip(); + return true; + } + } if (!plainIn.hasRemaining() && !cipherIn.hasRemaining()) { // need to try to read something cipherIn.clear(); diff --git a/src/main/java/com/rabbitmq/client/impl/nio/SslEngineFrameBuilder.java b/src/main/java/com/rabbitmq/client/impl/nio/SslEngineFrameBuilder.java index c2f1923874..48072988c2 100644 --- a/src/main/java/com/rabbitmq/client/impl/nio/SslEngineFrameBuilder.java +++ b/src/main/java/com/rabbitmq/client/impl/nio/SslEngineFrameBuilder.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -22,6 +22,7 @@ import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; + /** * Sub-class of {@link FrameBuilder} that unwraps crypted data from the network. * @since 4.4.0 @@ -32,20 +33,26 @@ public class SslEngineFrameBuilder extends FrameBuilder { private final ByteBuffer cipherBuffer; - public SslEngineFrameBuilder(SSLEngine sslEngine, ByteBuffer plainIn, ByteBuffer cipherIn, ReadableByteChannel channel) { - super(channel, plainIn); + private boolean isUnderflowHandlingEnabled = false; + + public SslEngineFrameBuilder(SSLEngine sslEngine, ByteBuffer plainIn, + ByteBuffer cipherIn, ReadableByteChannel channel, + int maxPayloadSize) { + super(channel, plainIn, maxPayloadSize); this.sslEngine = sslEngine; this.cipherBuffer = cipherIn; } @Override protected boolean somethingToRead() throws IOException { - if (applicationBuffer.hasRemaining()) { + if (applicationBuffer.hasRemaining() && !isUnderflowHandlingEnabled) { return true; } else { applicationBuffer.clear(); - while (true) { + boolean underflowHandling = false; + + try { SSLEngineResult result = sslEngine.unwrap(cipherBuffer, applicationBuffer); switch (result.getStatus()) { case OK: @@ -59,19 +66,23 @@ protected boolean somethingToRead() throws IOException { throw new SSLException("buffer overflow in read"); case BUFFER_UNDERFLOW: cipherBuffer.compact(); - int read = NioHelper.read(channel, cipherBuffer); - if (read == 0) { - return false; - } - cipherBuffer.flip(); - break; + underflowHandling = true; + return false; case CLOSED: throw new SSLException("closed in read"); default: throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); - } + } + } finally { + isUnderflowHandlingEnabled = underflowHandling; } + + return false; } } + @Override + public boolean isUnderflowHandlingEnabled() { + return isUnderflowHandlingEnabled; + } } diff --git a/src/main/java/com/rabbitmq/client/impl/nio/SslEngineHelper.java b/src/main/java/com/rabbitmq/client/impl/nio/SslEngineHelper.java index 1e7e3a0793..b7a535da87 100644 --- a/src/main/java/com/rabbitmq/client/impl/nio/SslEngineHelper.java +++ b/src/main/java/com/rabbitmq/client/impl/nio/SslEngineHelper.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2022 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -21,10 +21,13 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; -import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED; +import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_TASK; +import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP; import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING; /** @@ -32,27 +35,45 @@ */ public class SslEngineHelper { - public static boolean doHandshake(SocketChannel socketChannel, SSLEngine engine) throws IOException { + private static final Logger LOGGER = LoggerFactory.getLogger(SslEngineHelper.class); + + public static boolean doHandshake(WritableByteChannel writeChannel, ReadableByteChannel readChannel, SSLEngine engine) throws IOException { ByteBuffer plainOut = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()); ByteBuffer plainIn = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()); ByteBuffer cipherOut = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); ByteBuffer cipherIn = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); + LOGGER.debug("Starting TLS handshake"); + SSLEngineResult.HandshakeStatus handshakeStatus = engine.getHandshakeStatus(); + LOGGER.debug("Initial handshake status is {}", handshakeStatus); while (handshakeStatus != FINISHED && handshakeStatus != NOT_HANDSHAKING) { + LOGGER.debug("Handshake status is {}", handshakeStatus); switch (handshakeStatus) { case NEED_TASK: + LOGGER.debug("Running tasks"); handshakeStatus = runDelegatedTasks(engine); break; case NEED_UNWRAP: - handshakeStatus = unwrap(cipherIn, plainIn, socketChannel, engine); + LOGGER.debug("Unwrapping..."); + handshakeStatus = unwrap(cipherIn, plainIn, readChannel, engine); break; case NEED_WRAP: - handshakeStatus = wrap(plainOut, cipherOut, socketChannel, engine); + LOGGER.debug("Wrapping..."); + handshakeStatus = wrap(plainOut, cipherOut, writeChannel, engine); + break; + case FINISHED: break; + case NOT_HANDSHAKING: + break; + default: + throw new SSLException("Unexpected handshake status " + handshakeStatus); } } + + + LOGGER.debug("TLS handshake completed"); return true; } @@ -60,6 +81,7 @@ private static SSLEngineResult.HandshakeStatus runDelegatedTasks(SSLEngine sslEn // FIXME run in executor? Runnable runnable; while ((runnable = sslEngine.getDelegatedTask()) != null) { + LOGGER.debug("Running delegated task"); runnable.run(); } return sslEngine.getHandshakeStatus(); @@ -68,29 +90,57 @@ private static SSLEngineResult.HandshakeStatus runDelegatedTasks(SSLEngine sslEn private static SSLEngineResult.HandshakeStatus unwrap(ByteBuffer cipherIn, ByteBuffer plainIn, ReadableByteChannel channel, SSLEngine sslEngine) throws IOException { SSLEngineResult.HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); - - if (channel.read(cipherIn) < 0) { - throw new SSLException("Could not read from socket channel"); + LOGGER.debug("Handshake status is {} before unwrapping", handshakeStatus); + + LOGGER.debug("Cipher in position {}", cipherIn.position()); + int read; + if (cipherIn.position() == 0) { + LOGGER.debug("Reading from channel"); + read = channel.read(cipherIn); + LOGGER.debug("Read {} byte(s) from channel", read); + if (read < 0) { + throw new SSLException("Could not read from socket channel"); + } + cipherIn.flip(); + } else { + LOGGER.debug("Not reading"); } - cipherIn.flip(); SSLEngineResult.Status status; + SSLEngineResult unwrapResult; do { - SSLEngineResult unwrapResult = sslEngine.unwrap(cipherIn, plainIn); + int positionBeforeUnwrapping = cipherIn.position(); + unwrapResult = sslEngine.unwrap(cipherIn, plainIn); + LOGGER.debug("SSL engine result is {} after unwrapping", unwrapResult); status = unwrapResult.getStatus(); switch (status) { case OK: plainIn.clear(); - handshakeStatus = runDelegatedTasks(sslEngine); + if (unwrapResult.getHandshakeStatus() == NEED_TASK) { + handshakeStatus = runDelegatedTasks(sslEngine); + int newPosition = positionBeforeUnwrapping + unwrapResult.bytesConsumed(); + if (newPosition == cipherIn.limit()) { + LOGGER.debug("Clearing cipherIn because all bytes have been read and unwrapped"); + cipherIn.clear(); + } else { + LOGGER.debug("Setting cipherIn position to {} (limit is {})", newPosition, cipherIn.limit()); + cipherIn.position(positionBeforeUnwrapping + unwrapResult.bytesConsumed()); + } + } else { + handshakeStatus = unwrapResult.getHandshakeStatus(); + } break; case BUFFER_OVERFLOW: throw new SSLException("Buffer overflow during handshake"); case BUFFER_UNDERFLOW: + LOGGER.debug("Buffer underflow"); cipherIn.compact(); - int read = NioHelper.read(channel, cipherIn); + LOGGER.debug("Reading from channel..."); + read = NioHelper.read(channel, cipherIn); if(read <= 0) { retryRead(channel, cipherIn); } + LOGGER.debug("Done reading from channel..."); cipherIn.flip(); break; case CLOSED: @@ -100,9 +150,9 @@ private static SSLEngineResult.HandshakeStatus unwrap(ByteBuffer cipherIn, ByteB throw new SSLException("Unexpected status from " + unwrapResult); } } - while (cipherIn.hasRemaining()); + while (unwrapResult.getHandshakeStatus() != NEED_WRAP && unwrapResult.getHandshakeStatus() != FINISHED); - cipherIn.compact(); + LOGGER.debug("cipherIn position after unwrap {}", cipherIn.position()); return handshakeStatus; } @@ -127,36 +177,32 @@ private static int retryRead(ReadableByteChannel channel, ByteBuffer buffer) thr private static SSLEngineResult.HandshakeStatus wrap(ByteBuffer plainOut, ByteBuffer cipherOut, WritableByteChannel channel, SSLEngine sslEngine) throws IOException { SSLEngineResult.HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); - SSLEngineResult.Status status = sslEngine.wrap(plainOut, cipherOut).getStatus(); - switch (status) { + LOGGER.debug("Handshake status is {} before wrapping", handshakeStatus); + SSLEngineResult result = sslEngine.wrap(plainOut, cipherOut); + LOGGER.debug("SSL engine result is {} after wrapping", result); + switch (result.getStatus()) { case OK: - handshakeStatus = runDelegatedTasks(sslEngine); cipherOut.flip(); while (cipherOut.hasRemaining()) { - channel.write(cipherOut); + int written = channel.write(cipherOut); + LOGGER.debug("Wrote {} byte(s)", written); } cipherOut.clear(); + if (result.getHandshakeStatus() == NEED_TASK) { + handshakeStatus = runDelegatedTasks(sslEngine); + } else { + handshakeStatus = result.getHandshakeStatus(); + } + break; case BUFFER_OVERFLOW: throw new SSLException("Buffer overflow during handshake"); default: - throw new SSLException("Unexpected status " + status); + throw new SSLException("Unexpected status " + result.getStatus()); } return handshakeStatus; } - static int bufferCopy(ByteBuffer from, ByteBuffer to) { - int maxTransfer = Math.min(to.remaining(), from.remaining()); - - ByteBuffer temporaryBuffer = from.duplicate(); - temporaryBuffer.limit(temporaryBuffer.position() + maxTransfer); - to.put(temporaryBuffer); - - from.position(from.position() + maxTransfer); - - return maxTransfer; - } - public static void write(WritableByteChannel socketChannel, SSLEngine engine, ByteBuffer plainOut, ByteBuffer cypherOut) throws IOException { while (plainOut.hasRemaining()) { cypherOut.clear(); diff --git a/src/main/java/com/rabbitmq/client/impl/recovery/AutorecoveringConnection.java b/src/main/java/com/rabbitmq/client/impl/recovery/AutorecoveringConnection.java index 9cb0dbff59..743fdd8958 100644 --- a/src/main/java/com/rabbitmq/client/impl/recovery/AutorecoveringConnection.java +++ b/src/main/java/com/rabbitmq/client/impl/recovery/AutorecoveringConnection.java @@ -810,9 +810,9 @@ private void internalRecoverQueue(final String oldName, RecordedQueue q, boolean if (!oldName.equals(newName)) { // make sure queues are re-added with // their new names, if applicable. MK. + propagateQueueNameChangeToBindings(oldName, newName); + propagateQueueNameChangeToConsumers(oldName, newName); synchronized (this.recordedQueues) { - this.propagateQueueNameChangeToBindings(oldName, newName); - this.propagateQueueNameChangeToConsumers(oldName, newName); // bug26552: // remove old name after we've updated the bindings and consumers, deleteRecordedQueue(oldName); diff --git a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedEntity.java b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedEntity.java index a9fae4c3ae..a56f58b88a 100644 --- a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedEntity.java +++ b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedEntity.java @@ -20,7 +20,7 @@ /** * @since 3.3.0 */ -public class RecordedEntity { +public abstract class RecordedEntity { protected final AutorecoveringChannel channel; public RecordedEntity(AutorecoveringChannel channel) { diff --git a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedExchange.java b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedExchange.java index 7625b5a870..aaedcbbf58 100644 --- a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedExchange.java +++ b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedExchange.java @@ -31,6 +31,7 @@ public RecordedExchange(AutorecoveringChannel channel, String name) { super(channel, name); } + @Override public void recover() throws IOException { this.channel.getDelegate().exchangeDeclare(this.name, this.type, this.durable, this.autoDelete, this.arguments); } diff --git a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedNamedEntity.java b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedNamedEntity.java index 6ea8b6fa96..7b5a86a8f9 100644 --- a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedNamedEntity.java +++ b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedNamedEntity.java @@ -15,10 +15,11 @@ package com.rabbitmq.client.impl.recovery; +import java.io.IOException; /** * @since 3.3.0 */ -public class RecordedNamedEntity extends RecordedEntity { +public abstract class RecordedNamedEntity extends RecordedEntity { protected String name; public RecordedNamedEntity(AutorecoveringChannel channel, String name) { @@ -26,6 +27,8 @@ public RecordedNamedEntity(AutorecoveringChannel channel, String name) { this.name = name; } + public abstract void recover() throws IOException; + public String getName() { return name; } diff --git a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueue.java b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueue.java index 52caced2af..b41ecdc302 100644 --- a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueue.java +++ b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueue.java @@ -55,6 +55,7 @@ public boolean isServerNamed() { return this.serverNamed; } + @Override public void recover() throws IOException { this.name = this.channel.getDelegate().queueDeclare(this.getNameToUseForRecovery(), this.durable, @@ -71,7 +72,7 @@ public RecordedQueue durable(boolean value) { this.durable = value; return this; } - + public boolean isDurable() { return this.durable; } @@ -80,7 +81,7 @@ public RecordedQueue autoDelete(boolean value) { this.autoDelete = value; return this; } - + public boolean isAutoDelete() { return this.autoDelete; } diff --git a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueueBinding.java b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueueBinding.java index 12ed3d48bb..37bbb14fe5 100644 --- a/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueueBinding.java +++ b/src/main/java/com/rabbitmq/client/impl/recovery/RecordedQueueBinding.java @@ -27,7 +27,7 @@ public RecordedQueueBinding(AutorecoveringChannel channel) { @Override public void recover() throws IOException { - this.channel.getDelegate().queueBind(this.getDestination(), this.getSource(), this.routingKey, this.arguments); + this.channel.getDelegate().queueBind(this.destination, this.source, this.routingKey, this.arguments); } @Override diff --git a/src/test/java/com/rabbitmq/client/AbstractJsonRpcTest.java b/src/test/java/com/rabbitmq/client/AbstractJsonRpcTest.java index 0b6bc20a68..ec9fbd2f39 100644 --- a/src/test/java/com/rabbitmq/client/AbstractJsonRpcTest.java +++ b/src/test/java/com/rabbitmq/client/AbstractJsonRpcTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,8 +19,8 @@ import com.rabbitmq.tools.jsonrpc.JsonRpcClient; import com.rabbitmq.tools.jsonrpc.JsonRpcMapper; import com.rabbitmq.tools.jsonrpc.JsonRpcServer; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import java.util.Date; @@ -35,7 +35,7 @@ public abstract class AbstractJsonRpcTest { abstract JsonRpcMapper createMapper(); - @Before + @BeforeEach public void init() throws Exception { clientConnection = TestUtils.connectionFactory().newConnection(); clientChannel = clientConnection.createChannel(); @@ -57,7 +57,7 @@ public void init() throws Exception { service = client.createProxy(RpcService.class); } - @After + @AfterEach public void tearDown() throws Exception { if (server != null) { server.terminateMainloop(); diff --git a/src/test/java/com/rabbitmq/client/AmqpClientTestExtension.java b/src/test/java/com/rabbitmq/client/AmqpClientTestExtension.java new file mode 100644 index 0000000000..07e27a6838 --- /dev/null +++ b/src/test/java/com/rabbitmq/client/AmqpClientTestExtension.java @@ -0,0 +1,237 @@ +// Copyright (c) 2023 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client; + +import static org.junit.jupiter.api.extension.ConditionEvaluationResult.disabled; +import static org.junit.jupiter.api.extension.ConditionEvaluationResult.enabled; + +import com.rabbitmq.client.test.TestUtils; +import com.rabbitmq.client.test.functional.FunctionalTestSuite; +import com.rabbitmq.client.test.server.HaTestSuite; +import com.rabbitmq.client.test.server.LastHaTestSuite; +import com.rabbitmq.client.test.server.ServerTestSuite; +import com.rabbitmq.client.test.ssl.SslTestSuite; +import com.rabbitmq.tools.Host; +import java.io.File; +import java.lang.reflect.Field; +import java.net.Socket; +import java.util.Properties; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AmqpClientTestExtension implements ExecutionCondition, BeforeAllCallback, + BeforeEachCallback, + AfterEachCallback { + + private static final Logger LOGGER = LoggerFactory.getLogger(AmqpClientTestExtension.class); + private static final Namespace NAMESPACE = Namespace.create(AmqpClientTestExtension.class); + + static { + Properties TESTS_PROPS = new Properties(System.getProperties()); + String make = System.getenv("MAKE"); + if (make != null) { + TESTS_PROPS.setProperty("make.bin", make); + } + try { + TESTS_PROPS.load(Host.class.getClassLoader().getResourceAsStream("config.properties")); + } catch (Exception e) { + System.out.println( + "\"build.properties\" or \"config.properties\" not found" + + " in classpath. Please copy \"build.properties\" and" + + " \"config.properties\" into src/test/resources. Ignore" + + " this message if running with ant."); + } finally { + System.setProperties(TESTS_PROPS); + } + } + + private static void maybeSetHaFieldValue(ExtensionContext context, boolean value) { + if (context.getTestClass().isPresent() && context.getTestInstance().isPresent()) { + try { + Field haField = findField(context.getTestClass().get(), "ha"); + if (haField != null) { + haField.setAccessible(true); + haField.set(context.getTestInstance().get(), value); + } + } catch (Exception e) { + // OK + } + } + } + + private static Field findField(Class clazz, String fieldName) { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + if (clazz.getSuperclass() != null) { + return findField(clazz.getSuperclass(), fieldName); + } + } + return null; + } + + private static boolean isFunctionalSuite(ExtensionContext context) { + return isTestSuite(context, FunctionalTestSuite.class); + } + + private static boolean isSslSuite(ExtensionContext context) { + return isTestSuite(context, SslTestSuite.class); + } + + private static boolean isServerSuite(ExtensionContext context) { + return isTestSuite(context, ServerTestSuite.class); + } + + private static boolean isHaSuite(ExtensionContext context) { + return isTestSuite(context, HaTestSuite.class); + } + + private static boolean isLastHaSuite(ExtensionContext context) { + return isTestSuite(context, LastHaTestSuite.class); + } + + private static boolean isTestSuite(ExtensionContext context, Class clazz) { + return context.getUniqueId().contains(clazz.getName()); + } + + public static boolean requiredProperties() { + /* Path to rabbitmqctl. */ + String rabbitmqctl = Host.rabbitmqctlCommand(); + if (rabbitmqctl == null) { + System.err.println( + "rabbitmqctl required; please set \"rabbitmqctl.bin\" system" + + " property"); + return false; + } + + return true; + } + + public static boolean isSSLAvailable() { + String sslClientCertsDir = System.getProperty("test-client-cert.path"); + String hostname = System.getProperty("broker.hostname"); + String port = System.getProperty("broker.sslport"); + if (sslClientCertsDir == null || hostname == null || port == null) { + return false; + } + + // If certificate is present and some server is listening on port 5671 + if (new File(sslClientCertsDir).exists() && + checkServerListening(hostname, Integer.parseInt(port))) { + return true; + } else { + return false; + } + } + + private static boolean checkServerListening(String host, int port) { + Socket s = null; + try { + s = new Socket(host, port); + return true; + } catch (Exception e) { + return false; + } finally { + if (s != null) { + try { + s.close(); + } catch (Exception e) { + } + } + } + } + + private static Store store(ExtensionContext context) { + return context.getRoot().getStore(NAMESPACE); + } + + private static boolean hasHaSuiteStarted(ExtensionContext context) { + return "true".equals(store(context).get("ha")); + } + + private static void markHaSuiteStarted(ExtensionContext context) { + store(context).put("ha", "true"); + } + + private static void markHaSuiteFinished(ExtensionContext context) { + store(context).remove("ha"); + } + + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + // HA test suite must be checked first because it contains other test suites + if (isHaSuite(context)) { + return requiredProperties() ? enabled("Required properties available") + : disabled("Required properties not available"); + } else if (isServerSuite(context)) { + return requiredProperties() ? enabled("Required properties available") + : disabled("Required properties not available"); + } else if (isFunctionalSuite(context)) { + return requiredProperties() ? enabled("Required properties available") + : disabled("Required properties not available"); + } else if (isSslSuite(context)) { + return requiredProperties() && isSSLAvailable() ? enabled( + "Required properties and TLS available") + : disabled("Required properties or TLS not available"); + } + return enabled("ok"); + } + + @Override + public void beforeAll(ExtensionContext context) throws Exception { + if (isHaSuite(context) && !hasHaSuiteStarted(context)) { + LOGGER.info("Starting HA test suite"); + Host.rabbitmqctl("set_policy HA '.*' '{\"ha-mode\":\"all\"}'"); + markHaSuiteStarted(context); + } + if (isLastHaSuite(context)) { + LOGGER.info("HA suite done, clearing HA state"); + Host.rabbitmqctl("clear_policy HA"); + markHaSuiteFinished(context); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + LOGGER.info( + "Starting test: {}.{} (nio? {}, HA? {})", + context.getTestClass().get().getSimpleName(), context.getTestMethod().get().getName(), + TestUtils.USE_NIO, + hasHaSuiteStarted(context) + ); + if (isHaSuite(context)) { + maybeSetHaFieldValue(context, true); + } + } + + @Override + public void afterEach(ExtensionContext context) { + LOGGER.info("Test finished: {}.{}", + context.getTestClass().get().getSimpleName(), context.getTestMethod().get().getName()); + if (isHaSuite(context)) { + maybeSetHaFieldValue(context, false); + } + } + +} diff --git a/src/test/java/com/rabbitmq/client/DefaultJsonRpcTest.java b/src/test/java/com/rabbitmq/client/DefaultJsonRpcTest.java index 42cd9cfa66..7f231d1bd3 100644 --- a/src/test/java/com/rabbitmq/client/DefaultJsonRpcTest.java +++ b/src/test/java/com/rabbitmq/client/DefaultJsonRpcTest.java @@ -15,17 +15,17 @@ package com.rabbitmq.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import com.rabbitmq.tools.jsonrpc.DefaultJsonRpcMapper; import com.rabbitmq.tools.jsonrpc.JsonRpcException; import com.rabbitmq.tools.jsonrpc.JsonRpcMapper; -import org.junit.Test; import java.lang.reflect.UndeclaredThrowableException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; public class DefaultJsonRpcTest extends AbstractJsonRpcTest { diff --git a/src/test/java/com/rabbitmq/client/JacksonJsonRpcTest.java b/src/test/java/com/rabbitmq/client/JacksonJsonRpcTest.java index e7a57021d4..f926061f94 100644 --- a/src/test/java/com/rabbitmq/client/JacksonJsonRpcTest.java +++ b/src/test/java/com/rabbitmq/client/JacksonJsonRpcTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -18,16 +18,16 @@ import com.rabbitmq.tools.jsonrpc.JacksonJsonRpcMapper; import com.rabbitmq.tools.jsonrpc.JsonRpcException; import com.rabbitmq.tools.jsonrpc.JsonRpcMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.UndeclaredThrowableException; import java.util.Calendar; import java.util.Date; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class JacksonJsonRpcTest extends AbstractJsonRpcTest { diff --git a/src/test/java/com/rabbitmq/client/QueueingConsumer.java b/src/test/java/com/rabbitmq/client/QueueingConsumer.java index 33a033008f..9ecddaa67b 100644 --- a/src/test/java/com/rabbitmq/client/QueueingConsumer.java +++ b/src/test/java/com/rabbitmq/client/QueueingConsumer.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/impl/AMQConnectionRefreshCredentialsTest.java b/src/test/java/com/rabbitmq/client/impl/AMQConnectionRefreshCredentialsTest.java index 989ee69ffa..a5fce8a561 100644 --- a/src/test/java/com/rabbitmq/client/impl/AMQConnectionRefreshCredentialsTest.java +++ b/src/test/java/com/rabbitmq/client/impl/AMQConnectionRefreshCredentialsTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -18,12 +18,13 @@ import com.rabbitmq.client.Method; import com.rabbitmq.client.*; import com.rabbitmq.client.test.TestUtils; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TestRule; -import org.junit.runner.RunWith; +import com.rabbitmq.client.test.TestUtils.BrokerVersion; +import com.rabbitmq.client.test.TestUtils.BrokerVersionAtLeast; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import java.io.IOException; import java.time.Duration; @@ -38,18 +39,27 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) +@BrokerVersionAtLeast(BrokerVersion.RABBITMQ_3_8) public class AMQConnectionRefreshCredentialsTest { - @ClassRule - public static TestRule brokerVersionTestRule = TestUtils.atLeast38(); - @Mock CredentialsProvider credentialsProvider; @Mock CredentialsRefreshService refreshService; + AutoCloseable mocks; + + @BeforeEach + void init() { + mocks = MockitoAnnotations.openMocks(this); + } + + @AfterEach + void tearDown() throws Exception { + mocks.close(); + } + private static ConnectionFactory connectionFactoryThatSendsGarbageAfterUpdateSecret() { ConnectionFactory cf = new ConnectionFactory() { @Override diff --git a/src/test/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshServiceTest.java b/src/test/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshServiceTest.java index 3bd0cca640..2ad3681c52 100644 --- a/src/test/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshServiceTest.java +++ b/src/test/java/com/rabbitmq/client/impl/DefaultCredentialsRefreshServiceTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,10 +15,11 @@ package com.rabbitmq.client.impl; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; @@ -38,7 +39,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) public class DefaultCredentialsRefreshServiceTest { @Mock @@ -49,11 +49,19 @@ public class DefaultCredentialsRefreshServiceTest { DefaultCredentialsRefreshService refreshService; - @After - public void tearDown() { + AutoCloseable mocks; + + @BeforeEach + void init() { + this.mocks = MockitoAnnotations.openMocks(this); + } + + @AfterEach + public void tearDown() throws Exception { if (refreshService != null) { refreshService.close(); } + mocks.close(); } @Test diff --git a/src/test/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProviderTest.java b/src/test/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProviderTest.java index 0a08125d8f..f717cbcf27 100644 --- a/src/test/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProviderTest.java +++ b/src/test/java/com/rabbitmq/client/impl/OAuth2ClientCredentialsGrantCredentialsProviderTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,6 +15,7 @@ package com.rabbitmq.client.impl; +import com.google.gson.Gson; import com.rabbitmq.client.test.TestUtils; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; @@ -27,9 +28,9 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; @@ -62,7 +63,7 @@ static boolean isJava13() { return javaVersion != null && javaVersion.startsWith("13."); } - @Before + @BeforeEach public void init() { if (isJava13()) { // for Java 13.0.7, see https://github.com/bcgit/bc-java/issues/941 @@ -70,7 +71,7 @@ public void init() { } } - @After + @AfterEach public void tearDown() throws Exception { if (isJava13()) { System.setProperty("keystore.pkcs12.keyProtectionAlgorithm", ""); @@ -195,7 +196,7 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques } @Test - public void parseToken() { + public void parseTokenDefault() { OAuth2ClientCredentialsGrantCredentialsProvider provider = new OAuth2ClientCredentialsGrantCredentialsProvider( "http://localhost:8080/uaa/oauth/token/", "rabbit_client", "rabbit_secret", @@ -211,6 +212,36 @@ public void parseToken() { assertThat(token.getTimeBeforeExpiration()).isBetween(Duration.ofSeconds(expiresIn - 10), Duration.ofSeconds(expiresIn + 1)); } + @Test + public void parseTokenGson() { + Gson gson = new Gson(); + OAuth2ClientCredentialsGrantCredentialsProvider provider = new OAuth2ClientCredentialsGrantCredentialsProvider( + "http://localhost:8080/uaa/oauth/token/", + "rabbit_client", "rabbit_secret", + "client_credentials" + ) { + @Override + protected Token parseToken(String response) { + try { + Map map = gson.fromJson(response, Map.class); + int expiresIn = ((Number) map.get("expires_in")).intValue(); + Instant receivedAt = Instant.now(); + return new Token(map.get("access_token").toString(), expiresIn, receivedAt); + } catch (Exception e) { + throw new OAuthTokenManagementException("Error while parsing OAuth 2 token", e); + } + } + }; + + String accessToken = "18c1b1dfdda04382a8bcc14d077b71dd"; + int expiresIn = 43199; + String response = sampleJsonToken(accessToken, expiresIn); + + OAuth2ClientCredentialsGrantCredentialsProvider.Token token = provider.parseToken(response); + assertThat(token.getAccess()).isEqualTo("18c1b1dfdda04382a8bcc14d077b71dd"); + assertThat(token.getTimeBeforeExpiration()).isBetween(Duration.ofSeconds(expiresIn - 10), Duration.ofSeconds(expiresIn + 1)); + } + String sampleJsonToken(String accessToken, int expiresIn) { String json = "{\n" + " \"access_token\" : \"{accessToken}\",\n" + diff --git a/src/test/java/com/rabbitmq/client/impl/RefreshProtectedCredentialsProviderTest.java b/src/test/java/com/rabbitmq/client/impl/RefreshProtectedCredentialsProviderTest.java index a65ed3b6ca..dfed27341d 100644 --- a/src/test/java/com/rabbitmq/client/impl/RefreshProtectedCredentialsProviderTest.java +++ b/src/test/java/com/rabbitmq/client/impl/RefreshProtectedCredentialsProviderTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.impl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.Set; diff --git a/src/test/java/com/rabbitmq/client/impl/ValueWriterTest.java b/src/test/java/com/rabbitmq/client/impl/ValueWriterTest.java index ea0d94c683..54a9acfe55 100644 --- a/src/test/java/com/rabbitmq/client/impl/ValueWriterTest.java +++ b/src/test/java/com/rabbitmq/client/impl/ValueWriterTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,49 +15,43 @@ package com.rabbitmq.client.impl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ValueWriterTest { - @Test(expected = IllegalArgumentException.class) - public void writingOverlyLargeBigDecimalShouldFail() - throws IOException { - - OutputStream outputStream = new OutputStream() { - @Override - public void write(int b) { - } - }; - - DataOutputStream dataOutputStream = new DataOutputStream(outputStream); - - ValueWriter valueWriter = new ValueWriter(dataOutputStream); - - valueWriter.writeFieldValue(new BigDecimal(Integer.MAX_VALUE).add(new BigDecimal(1))); - + @Test + public void writingOverlyLargeBigDecimalShouldFail() { + assertThatThrownBy(() -> { + OutputStream outputStream = new OutputStream() { + @Override + public void write(int b) { + } + }; + DataOutputStream dataOutputStream = new DataOutputStream(outputStream); + ValueWriter valueWriter = new ValueWriter(dataOutputStream); + valueWriter.writeFieldValue(new BigDecimal(Integer.MAX_VALUE).add(new BigDecimal(1))); + }).isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) - public void writingOverlyLargeScaleInBigDecimalShouldFail() - throws IOException { - - OutputStream outputStream = new OutputStream() { - @Override - public void write(int b) { - } - }; - - DataOutputStream dataOutputStream = new DataOutputStream(outputStream); - - ValueWriter valueWriter = new ValueWriter(dataOutputStream); - - valueWriter.writeFieldValue(new BigDecimal(BigInteger.ONE, 500)); + @Test + public void writingOverlyLargeScaleInBigDecimalShouldFail() { + assertThatThrownBy(() -> { + OutputStream outputStream = new OutputStream() { + @Override + public void write(int b) { + } + }; + DataOutputStream dataOutputStream = new DataOutputStream(outputStream); + ValueWriter valueWriter = new ValueWriter(dataOutputStream); + valueWriter.writeFieldValue(new BigDecimal(BigInteger.ONE, 500)); + }).isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/src/test/java/com/rabbitmq/client/impl/WorkPoolTests.java b/src/test/java/com/rabbitmq/client/impl/WorkPoolTests.java index 4cc054ca88..54a49da485 100644 --- a/src/test/java/com/rabbitmq/client/impl/WorkPoolTests.java +++ b/src/test/java/com/rabbitmq/client/impl/WorkPoolTests.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,15 +15,15 @@ package com.rabbitmq.client.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit tests for {@link WorkPool} @@ -34,9 +34,8 @@ public class WorkPoolTests { /** * Test unknown key tolerated silently - * @throws Exception untested */ - @Test public void unknownKey() throws Exception{ + @Test public void unknownKey() { assertFalse(this.pool.addWorkItem("test", new Object())); } @@ -58,16 +57,15 @@ public class WorkPoolTests { assertEquals(1, workList.size()); assertEquals(one, workList.get(0)); - assertTrue("Should be made ready", this.pool.finishWorkBlock(key)); + assertTrue(this.pool.finishWorkBlock(key), "Should be made ready"); workList.clear(); key = this.pool.nextWorkBlock(workList, 1); - assertEquals("Work client key wrong", "test", key); - assertEquals("Wrong work delivered", two, workList.get(0)); - - assertFalse("Should not be made ready after this.", this.pool.finishWorkBlock(key)); + assertEquals("test", key, "Work client key wrong"); + assertEquals(two, workList.get(0), "Wrong work delivered"); - assertNull("Shouldn't be more work", this.pool.nextWorkBlock(workList, 1)); + assertFalse(this.pool.finishWorkBlock(key), "Should not be made ready after this."); + assertNull(this.pool.nextWorkBlock(workList, 1), "Shouldn't be more work"); } /** diff --git a/src/test/java/com/rabbitmq/client/test/AMQBuilderApiTest.java b/src/test/java/com/rabbitmq/client/test/AMQBuilderApiTest.java index 46241c38b3..a4b54c9fa7 100644 --- a/src/test/java/com/rabbitmq/client/test/AMQBuilderApiTest.java +++ b/src/test/java/com/rabbitmq/client/test/AMQBuilderApiTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -14,12 +14,12 @@ // info@rabbitmq.com. package com.rabbitmq.client.test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Method; @@ -38,7 +38,7 @@ public class AMQBuilderApiTest extends BrokerTestCase .build() ).getMethod(); - assertTrue("Channel should still be open.", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should still be open."); assertTrue(retVal instanceof AMQP.Exchange.DeclareOk); retVal = channel.rpc(new AMQP.Exchange.Delete.Builder() @@ -46,7 +46,7 @@ public class AMQBuilderApiTest extends BrokerTestCase .build() ).getMethod(); - assertTrue("Channel should still be open.", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should still be open."); assertTrue(retVal instanceof AMQP.Exchange.DeleteOk); } @@ -59,14 +59,14 @@ public class AMQBuilderApiTest extends BrokerTestCase .build() ); - assertTrue("Channel should still be open.", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should still be open."); channel.asyncRpc(new AMQP.Exchange.Delete.Builder() .exchange(XCHG_NAME) .build() ); - assertTrue("Channel should still be open.", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should still be open."); } @Test public void illFormedBuilder() diff --git a/src/test/java/com/rabbitmq/client/test/AMQChannelTest.java b/src/test/java/com/rabbitmq/client/test/AMQChannelTest.java index 0ea1a89c60..091e1b14c2 100644 --- a/src/test/java/com/rabbitmq/client/test/AMQChannelTest.java +++ b/src/test/java/com/rabbitmq/client/test/AMQChannelTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -23,9 +23,9 @@ import com.rabbitmq.client.impl.AMQCommand; import com.rabbitmq.client.impl.AMQConnection; import com.rabbitmq.client.impl.AMQImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.Callable; @@ -41,11 +41,11 @@ public class AMQChannelTest { ScheduledExecutorService scheduler; - @Before public void init() { + @BeforeEach public void init() { scheduler = Executors.newSingleThreadScheduledExecutor(); } - @After public void tearDown() { + @AfterEach public void tearDown() { scheduler.shutdownNow(); } diff --git a/src/test/java/com/rabbitmq/client/test/AMQConnectionTest.java b/src/test/java/com/rabbitmq/client/test/AMQConnectionTest.java index e36631de7c..de50c74542 100644 --- a/src/test/java/com/rabbitmq/client/test/AMQConnectionTest.java +++ b/src/test/java/com/rabbitmq/client/test/AMQConnectionTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,9 +20,9 @@ import com.rabbitmq.client.impl.ConnectionParams; import com.rabbitmq.client.impl.Frame; import com.rabbitmq.client.impl.FrameHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.InetAddress; @@ -36,8 +36,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test suite for AMQConnection. @@ -51,14 +51,14 @@ public class AMQConnectionTest { private ConnectionFactory factory; private MyExceptionHandler exceptionHandler; - @Before public void setUp() { + @BeforeEach public void setUp() { _mockFrameHandler = new MockFrameHandler(); factory = TestUtils.connectionFactory(); exceptionHandler = new MyExceptionHandler(); factory.setExceptionHandler(exceptionHandler); } - @After public void tearDown() { + @AfterEach public void tearDown() { factory = null; _mockFrameHandler = null; } @@ -159,8 +159,8 @@ public class AMQConnectionTest { } assertEquals(1, this._mockFrameHandler.countHeadersSent()); List exceptionList = exceptionHandler.getHandledExceptions(); - assertEquals("Only one exception expected", 1, exceptionList.size()); - assertEquals("Wrong type of exception returned.", SocketTimeoutException.class, exceptionList.get(0).getClass()); + assertEquals(1, exceptionList.size(), "Only one exception expected"); + assertEquals(SocketTimeoutException.class, exceptionList.get(0).getClass(), "Wrong type of exception returned."); } @Test public void clientProvidedConnectionName() throws IOException, TimeoutException { diff --git a/src/test/java/com/rabbitmq/client/test/AbstractRMQTestSuite.java b/src/test/java/com/rabbitmq/client/test/AbstractRMQTestSuite.java deleted file mode 100644 index 922b6b9931..0000000000 --- a/src/test/java/com/rabbitmq/client/test/AbstractRMQTestSuite.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. -// -// This software, the RabbitMQ Java client library, is triple-licensed under the -// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 -// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see -// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, -// please see LICENSE-APACHE2. -// -// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, -// either express or implied. See the LICENSE file for specific language governing -// rights and limitations of this software. -// -// If you have any questions regarding licensing, please contact us at -// info@rabbitmq.com. - -package com.rabbitmq.client.test; - -import com.rabbitmq.tools.Host; - -import java.io.File; -import java.io.IOException; -import java.net.Socket; -import java.util.Properties; - -public abstract class AbstractRMQTestSuite { - - static { - Properties TESTS_PROPS = new Properties(System.getProperties()); - String make = System.getenv("MAKE"); - if (make != null) - TESTS_PROPS.setProperty("make.bin", make); - try { - TESTS_PROPS.load(Host.class.getClassLoader().getResourceAsStream("config.properties")); - } catch (Exception e) { - System.out.println( - "\"build.properties\" or \"config.properties\" not found" + - " in classpath. Please copy \"build.properties\" and" + - " \"config.properties\" into src/test/resources. Ignore" + - " this message if running with ant."); - } finally { - System.setProperties(TESTS_PROPS); - } - } - - public static boolean requiredProperties() { - /* Path to rabbitmqctl. */ - String rabbitmqctl = Host.rabbitmqctlCommand(); - if (rabbitmqctl == null) { - System.err.println( - "rabbitmqctl required; please set \"rabbitmqctl.bin\" system" + - " property"); - return false; - } - - return true; - } - - public static boolean isSSLAvailable() { - String sslClientCertsDir = System.getProperty("test-client-cert.path"); - String hostname = System.getProperty("broker.hostname"); - String port = System.getProperty("broker.sslport"); - if (sslClientCertsDir == null || hostname == null || port == null) - return false; - - // If certificate is present and some server is listening on port 5671 - if (new File(sslClientCertsDir).exists() && - checkServerListening(hostname, Integer.parseInt(port))) { - return true; - } else - return false; - } - - private static boolean checkServerListening(String host, int port) { - Socket s = null; - try { - s = new Socket(host, port); - return true; - } catch (Exception e) { - return false; - } finally { - if (s != null) - try { - s.close(); - } catch (Exception e) { - } - } - } -} diff --git a/src/test/java/com/rabbitmq/client/test/AddressTest.java b/src/test/java/com/rabbitmq/client/test/AddressTest.java index 631dc5d986..bc9e860e8b 100644 --- a/src/test/java/com/rabbitmq/client/test/AddressTest.java +++ b/src/test/java/com/rabbitmq/client/test/AddressTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,11 +16,12 @@ package com.rabbitmq.client.test; import com.rabbitmq.client.Address; -import org.junit.Test; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -73,10 +74,11 @@ public class AddressTest { assertEquals(addr("[::1]", 5673), Address.parseAddress("[::1]:5673")); } - @Test(expected = IllegalArgumentException.class) + @Test public void parseUnquotedIPv6() { // using a non-quoted IPv6 addresses with a port - Address.parseAddress("::1:5673"); + Assertions.assertThatThrownBy(() -> Address.parseAddress("::1:5673")) + .isInstanceOf(IllegalArgumentException.class); } private Address addr(String addr) { diff --git a/src/test/java/com/rabbitmq/client/test/AmqpUriTest.java b/src/test/java/com/rabbitmq/client/test/AmqpUriTest.java index d5be86e4ee..f81ee0ea5c 100644 --- a/src/test/java/com/rabbitmq/client/test/AmqpUriTest.java +++ b/src/test/java/com/rabbitmq/client/test/AmqpUriTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,8 +15,8 @@ package com.rabbitmq.client.test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.net.URISyntaxException; import java.security.KeyManagementException; @@ -24,7 +24,7 @@ import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.ConnectionFactory; diff --git a/src/test/java/com/rabbitmq/client/test/BlockingCellTest.java b/src/test/java/com/rabbitmq/client/test/BlockingCellTest.java index b5c7e9a3b0..03334570a6 100644 --- a/src/test/java/com/rabbitmq/client/test/BlockingCellTest.java +++ b/src/test/java/com/rabbitmq/client/test/BlockingCellTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,12 +17,12 @@ package com.rabbitmq.client.test; import com.rabbitmq.utility.BlockingCell; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class BlockingCellTest { diff --git a/src/test/java/com/rabbitmq/client/test/BrokenFramesTest.java b/src/test/java/com/rabbitmq/client/test/BrokenFramesTest.java index 0ea3a02793..c0be492ae7 100644 --- a/src/test/java/com/rabbitmq/client/test/BrokenFramesTest.java +++ b/src/test/java/com/rabbitmq/client/test/BrokenFramesTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -23,9 +23,9 @@ import com.rabbitmq.client.impl.AMQImpl.Basic.Publish; import com.rabbitmq.client.impl.Frame; import com.rabbitmq.client.impl.FrameHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.InetAddress; @@ -35,19 +35,19 @@ import java.util.List; import java.util.concurrent.Executors; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class BrokenFramesTest { private MyFrameHandler myFrameHandler; private ConnectionFactory factory; - @Before public void setUp() { + @BeforeEach public void setUp() { myFrameHandler = new MyFrameHandler(); factory = TestUtils.connectionFactory(); } - @After public void tearDown() { + @AfterEach public void tearDown() { factory = null; myFrameHandler = null; } diff --git a/src/test/java/com/rabbitmq/client/test/BrokerTestCase.java b/src/test/java/com/rabbitmq/client/test/BrokerTestCase.java index 7c23a3c0e6..46763e78cc 100644 --- a/src/test/java/com/rabbitmq/client/test/BrokerTestCase.java +++ b/src/test/java/com/rabbitmq/client/test/BrokerTestCase.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -13,49 +13,28 @@ // If you have any questions regarding licensing, please contact us at // info@rabbitmq.com. - package com.rabbitmq.client.test; import com.rabbitmq.client.*; import com.rabbitmq.client.impl.nio.NioParams; import com.rabbitmq.tools.Host; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInfo; + import java.io.IOException; -import java.security.NoSuchAlgorithmException; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.*; -import static org.junit.Assume.*; +import static org.junit.jupiter.api.Assertions.*; public class BrokerTestCase { - private static final Logger LOGGER = LoggerFactory.getLogger(BrokerTestCase.class); - - @Rule - public TestRule watcher = new TestWatcher() { - protected void starting(Description description) { - LOGGER.info( - "Starting test: {}.{} (nio? {})", - description.getTestClass().getSimpleName(), description.getMethodName(), TestUtils.USE_NIO - ); - } + private boolean ha = false; - @Override - protected void finished(Description description) { - LOGGER.info("Test finished: {}.{}", description.getTestClass().getSimpleName(), description.getMethodName()); - } - }; + protected volatile TestInfo testInfo; protected ConnectionFactory connectionFactory = newConnectionFactory(); @@ -79,16 +58,19 @@ protected boolean isAutomaticRecoveryEnabled() { protected Connection connection; protected Channel channel; - @Before public void setUp() - throws IOException, TimeoutException { - assumeTrue(shouldRun()); + @BeforeEach + public void setUp(TestInfo testInfo) throws IOException, TimeoutException { + + + Assumptions.assumeTrue(shouldRun()); + this.testInfo = testInfo; openConnection(); openChannel(); createResources(); } - @After public void tearDown() + @AfterEach public void tearDown(TestInfo testInfo) throws IOException, TimeoutException { if(shouldRun()) { closeChannel(); @@ -134,9 +116,9 @@ protected void releaseResources() protected void restart() throws IOException, TimeoutException { - tearDown(); + tearDown(this.testInfo); bareRestart(); - setUp(); + setUp(this.testInfo); } protected void bareRestart() @@ -341,14 +323,24 @@ protected void unblock() throws IOException, InterruptedException { } protected String generateQueueName() { - return "queue" + UUID.randomUUID().toString(); + return name("queue", this.testInfo.getTestClass().get(), + this.testInfo.getTestMethod().get().getName()); } protected String generateExchangeName() { - return "exchange" + UUID.randomUUID().toString(); + return name("exchange", this.testInfo.getTestClass().get(), + this.testInfo.getTestMethod().get().getName()); } - protected SSLContext getSSLContext() throws NoSuchAlgorithmException { - return TestUtils.getSSLContext(); + private static String name(String prefix, Class testClass, String testMethodName) { + String uuid = UUID.randomUUID().toString(); + return String.format( + "%s_%s_%s%s", + prefix, testClass.getSimpleName(), testMethodName, uuid.substring(uuid.length() / 2)); } + + protected boolean ha() { + return this.ha; + } + } diff --git a/src/test/java/com/rabbitmq/client/test/Bug20004Test.java b/src/test/java/com/rabbitmq/client/test/Bug20004Test.java index 63e237d4b1..a62598165b 100644 --- a/src/test/java/com/rabbitmq/client/test/Bug20004Test.java +++ b/src/test/java/com/rabbitmq/client/test/Bug20004Test.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,66 +15,55 @@ package com.rabbitmq.client.test; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; - -import static org.junit.Assert.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; /** - * Test for bug 20004 - deadlock through internal synchronization on - * the channel object. This is more properly a unit test, but since it - * requires a connection to a broker, it's grouped with the functional - * tests. - *

- * Test calls channel.queueDeclare, while synchronising on channel, from - * an independent thread. + * Test for bug 20004 - deadlock through internal synchronization on the channel object. This is + * more properly a unit test, but since it requires a connection to a broker, it's grouped with the + * functional tests. + * + *

Test calls channel.queueDeclare, while synchronising on channel, from an independent thread. */ public class Bug20004Test extends BrokerTestCase { - private volatile Exception caughtException = null; - private volatile boolean completed = false; - private volatile boolean created = false; + private volatile Exception caughtException = null; + private volatile boolean created = false; - protected void releaseResources() - throws IOException - { - if (created) { - channel.queueDelete("Bug20004Test"); - } + protected void releaseResources() throws IOException { + if (created) { + channel.queueDelete("Bug20004Test"); } + } - @SuppressWarnings("deprecation") - @Test public void bug20004() throws IOException - { - final Bug20004Test testInstance = this; + @Test + public void bug20004() throws InterruptedException { + final Bug20004Test testInstance = this; + CountDownLatch completedLatch = new CountDownLatch(1); - Thread declaringThread = new Thread(new Runnable() { - public void run() { - try { - synchronized (channel) { - channel.queueDeclare("Bug20004Test", false, false, false, null); - testInstance.created = true; - } - } catch (Exception e) { - testInstance.caughtException = e; + Thread declaringThread = + new Thread( + () -> { + try { + synchronized (channel) { + channel.queueDeclare("Bug20004Test", false, false, false, null); + testInstance.created = true; } - testInstance.completed = true; - } - }); - declaringThread.start(); - - // poll (100ms) for `completed`, up to 5s - long endTime = System.currentTimeMillis() + 5000; - while (!completed && (System.currentTimeMillis() < endTime)) { - try { - Thread.sleep(100); - } catch (InterruptedException ie) {} - } + } catch (Exception e) { + testInstance.caughtException = e; + } + completedLatch.countDown(); + }); + declaringThread.start(); - declaringThread.stop(); // see bug 20012. + boolean completed = completedLatch.await(5, TimeUnit.SECONDS); - assertTrue("Deadlock detected?", completed); - assertNull("queueDeclare threw an exception", caughtException); - assertTrue("unknown sequence of events", created); - } + assertTrue(completed, "Deadlock detected?"); + assertNull(caughtException, "queueDeclare threw an exception"); + assertTrue(created, "unknown sequence of events"); + } } diff --git a/src/test/java/com/rabbitmq/client/test/ChannelAsyncCompletableFutureTest.java b/src/test/java/com/rabbitmq/client/test/ChannelAsyncCompletableFutureTest.java index a871d49455..b3e5592dd4 100644 --- a/src/test/java/com/rabbitmq/client/test/ChannelAsyncCompletableFutureTest.java +++ b/src/test/java/com/rabbitmq/client/test/ChannelAsyncCompletableFutureTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2017-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,15 +19,15 @@ import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.impl.AMQImpl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.UUID; import java.util.concurrent.*; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ChannelAsyncCompletableFutureTest extends BrokerTestCase { diff --git a/src/test/java/com/rabbitmq/client/test/ChannelNTest.java b/src/test/java/com/rabbitmq/client/test/ChannelNTest.java index 1568881016..448f94ee02 100644 --- a/src/test/java/com/rabbitmq/client/test/ChannelNTest.java +++ b/src/test/java/com/rabbitmq/client/test/ChannelNTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,9 +17,9 @@ import com.rabbitmq.client.Method; import com.rabbitmq.client.impl.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; @@ -36,13 +36,13 @@ public class ChannelNTest { ConsumerWorkService consumerWorkService; ExecutorService executorService; - @Before + @BeforeEach public void init() { executorService = Executors.newSingleThreadExecutor(); consumerWorkService = new ConsumerWorkService(executorService, null, 1000, 1000); } - @After + @AfterEach public void tearDown() { consumerWorkService.shutdown(); executorService.shutdownNow(); @@ -56,11 +56,12 @@ public void serverBasicCancelForUnknownConsumerDoesNotThrowException() throws Ex channel.processAsync(new AMQCommand(method)); } - @Test(expected = IOException.class) + @Test public void callingBasicCancelForUnknownConsumerThrowsException() throws Exception { AMQConnection connection = Mockito.mock(AMQConnection.class); ChannelN channel = new ChannelN(connection, 1, consumerWorkService); - channel.basicCancel("does-not-exist"); + assertThatThrownBy(() -> channel.basicCancel("does-not-exist")) + .isInstanceOf(IOException.class); } @Test diff --git a/src/test/java/com/rabbitmq/client/test/ChannelNumberAllocationTests.java b/src/test/java/com/rabbitmq/client/test/ChannelNumberAllocationTests.java index aa916529d7..76ecd0abda 100644 --- a/src/test/java/com/rabbitmq/client/test/ChannelNumberAllocationTests.java +++ b/src/test/java/com/rabbitmq/client/test/ChannelNumberAllocationTests.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -18,16 +18,16 @@ import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class ChannelNumberAllocationTests { static final int CHANNEL_COUNT = 100; @@ -41,11 +41,11 @@ public int compare(Channel x, Channel y){ Connection connection; - @Before public void setUp() throws Exception{ + @BeforeEach public void setUp() throws Exception{ connection = TestUtils.connectionFactory().newConnection(); } - @After public void tearDown() throws Exception{ + @AfterEach public void tearDown() throws Exception{ connection.close(); connection = null; } @@ -81,10 +81,10 @@ public int compare(Channel x, Channel y){ // In the current implementation the allocated numbers need not be increasing Collections.sort(channels, COMPARATOR); - assertEquals("Didn't create the right number of channels!", CHANNEL_COUNT, channels.size()); + assertEquals(CHANNEL_COUNT, channels.size(), "Didn't create the right number of channels!"); for(int i = 1; i < CHANNEL_COUNT; ++i) { - assertTrue("Channel numbers should be distinct." - , channels.get(i-1).getChannelNumber() < channels.get(i).getChannelNumber() + assertTrue(channels.get(i-1).getChannelNumber() < channels.get(i).getChannelNumber(), + "Channel numbers should be distinct." ); } } diff --git a/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java b/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java index 2e9c4bf9ed..d2f3aafcba 100644 --- a/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java +++ b/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,9 +17,9 @@ import com.rabbitmq.client.*; import com.rabbitmq.client.impl.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.net.SocketFactory; import java.io.IOException; @@ -36,12 +36,12 @@ public class ChannelRpcTimeoutIntegrationTest { ConnectionFactory factory; - @Before + @BeforeEach public void setUp() { factory = TestUtils.connectionFactory(); } - @After + @AfterEach public void tearDown() { factory = null; } diff --git a/src/test/java/com/rabbitmq/client/test/ClientTests.java b/src/test/java/com/rabbitmq/client/test/ClientTestSuite.java similarity index 90% rename from src/test/java/com/rabbitmq/client/test/ClientTests.java rename to src/test/java/com/rabbitmq/client/test/ClientTestSuite.java index 681542ab70..9a06f67f5d 100644 --- a/src/test/java/com/rabbitmq/client/test/ClientTests.java +++ b/src/test/java/com/rabbitmq/client/test/ClientTestSuite.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -13,7 +13,6 @@ // If you have any questions regarding licensing, please contact us at // info@rabbitmq.com. - package com.rabbitmq.client.test; import com.rabbitmq.client.JacksonJsonRpcTest; @@ -24,11 +23,12 @@ import com.rabbitmq.client.impl.ValueWriterTest; import com.rabbitmq.client.impl.*; import com.rabbitmq.utility.IntAllocatorTests; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -@RunWith(Suite.class) -@Suite.SuiteClasses({ +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ TableTest.class, LongStringTest.class, BlockingCellTest.class, @@ -83,11 +83,6 @@ RefreshCredentialsTest.class, AMQConnectionRefreshCredentialsTest.class }) -public class ClientTests { - - // initialize system properties - static{ - new AbstractRMQTestSuite(){}; - } +public class ClientTestSuite { } diff --git a/src/test/java/com/rabbitmq/client/test/ClientVersionTest.java b/src/test/java/com/rabbitmq/client/test/ClientVersionTest.java index c2c39284e3..3b66ec34fa 100644 --- a/src/test/java/com/rabbitmq/client/test/ClientVersionTest.java +++ b/src/test/java/com/rabbitmq/client/test/ClientVersionTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2017-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,7 +16,7 @@ package com.rabbitmq.client.test; import com.rabbitmq.client.impl.ClientVersion; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; diff --git a/src/test/java/com/rabbitmq/client/test/ClonePropertiesTest.java b/src/test/java/com/rabbitmq/client/test/ClonePropertiesTest.java index aae4d10e28..0ba413e9e8 100644 --- a/src/test/java/com/rabbitmq/client/test/ClonePropertiesTest.java +++ b/src/test/java/com/rabbitmq/client/test/ClonePropertiesTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,10 +17,10 @@ import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.MessageProperties; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ClonePropertiesTest { diff --git a/src/test/java/com/rabbitmq/client/test/CloseInMainLoop.java b/src/test/java/com/rabbitmq/client/test/CloseInMainLoop.java index 00e9570136..b340f472c4 100644 --- a/src/test/java/com/rabbitmq/client/test/CloseInMainLoop.java +++ b/src/test/java/com/rabbitmq/client/test/CloseInMainLoop.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.CountDownLatch; @@ -25,7 +25,7 @@ import javax.net.SocketFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/ConfirmBase.java b/src/test/java/com/rabbitmq/client/test/ConfirmBase.java index 144ab68564..425965b17a 100644 --- a/src/test/java/com/rabbitmq/client/test/ConfirmBase.java +++ b/src/test/java/com/rabbitmq/client/test/ConfirmBase.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.ExecutionException; @@ -25,8 +25,8 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.ShutdownSignalException; +import org.opentest4j.AssertionFailedError; -import junit.framework.AssertionFailedError; public class ConfirmBase extends BrokerTestCase { protected void waitForConfirms() throws Exception diff --git a/src/test/java/com/rabbitmq/client/test/ConnectionFactoryTest.java b/src/test/java/com/rabbitmq/client/test/ConnectionFactoryTest.java index a31a4b2ac4..39cc92493d 100644 --- a/src/test/java/com/rabbitmq/client/test/ConnectionFactoryTest.java +++ b/src/test/java/com/rabbitmq/client/test/ConnectionFactoryTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,7 @@ import com.rabbitmq.client.*; import com.rabbitmq.client.impl.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; @@ -96,7 +96,7 @@ protected synchronized FrameHandlerFactory createFrameHandlerFactory() { } @Test - public void shouldNotUseDnsResolutionWhenOneAddressAndNoTls() throws Exception { + public void shouldUseDnsResolutionWhenOneAddressAndNoTls() throws Exception { AMQConnection connection = mock(AMQConnection.class); AtomicReference addressResolver = new AtomicReference<>(); @@ -123,12 +123,11 @@ protected synchronized FrameHandlerFactory createFrameHandlerFactory() { doNothing().when(connection).start(); connectionFactory.newConnection(); - assertThat(addressResolver.get()).isNotNull().isInstanceOf(DnsRecordIpAddressResolver.class); } @Test - public void shouldNotUseDnsResolutionWhenOneAddressAndTls() throws Exception { + public void shouldUseDnsResolutionWhenOneAddressAndTls() throws Exception { AMQConnection connection = mock(AMQConnection.class); AtomicReference addressResolver = new AtomicReference<>(); @@ -157,7 +156,7 @@ protected synchronized FrameHandlerFactory createFrameHandlerFactory() { connectionFactory.useSslProtocol(); connectionFactory.newConnection(); - assertThat(addressResolver.get()).isNotNull().isInstanceOf(ListAddressResolver.class); + assertThat(addressResolver.get()).isNotNull().isInstanceOf(DnsRecordIpAddressResolver.class); } @Test diff --git a/src/test/java/com/rabbitmq/client/test/ConnectionTest.java b/src/test/java/com/rabbitmq/client/test/ConnectionTest.java index 8fb1c82059..e7233d6e86 100644 --- a/src/test/java/com/rabbitmq/client/test/ConnectionTest.java +++ b/src/test/java/com/rabbitmq/client/test/ConnectionTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,11 +17,12 @@ import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.stubbing.OngoingStubbing; @@ -29,16 +30,13 @@ import java.util.NoSuchElementException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.openMocks; -@RunWith(Parameterized.class) public class ConnectionTest { - @Parameterized.Parameter - public TestConfigurator configurator; @Mock MyConnection c = mock(MyConnection.class); @Mock @@ -46,23 +44,23 @@ public class ConnectionTest { AutoCloseable mocks; - @Parameterized.Parameters public static Object[] configurators() { return new Object[]{new NotNumberedChannelCreationCallback(), new NumberedChannelCreationCallback()}; } - @Before + @BeforeEach public void init() { mocks = openMocks(this); } - @After + @AfterEach public void tearDown() throws Exception { mocks.close(); } - @Test - public void openChannelWithNonNullChannelShouldReturnNonEmptyOptional() throws Exception { + @ParameterizedTest + @MethodSource("configurators") + public void openChannelWithNonNullChannelShouldReturnNonEmptyOptional(TestConfigurator configurator) throws Exception { configurator.mockAndWhenChannel(c).thenReturn(ch); configurator.mockAndWhenOptional(c).thenCallRealMethod(); Optional optional = configurator.open(c); @@ -70,20 +68,24 @@ public void openChannelWithNonNullChannelShouldReturnNonEmptyOptional() throws E assertSame(ch, optional.get()); } - @Test(expected = NoSuchElementException.class) - public void openChannelWithNullChannelShouldReturnEmptyOptional() throws Exception { + @ParameterizedTest + @MethodSource("configurators") + public void openChannelWithNullChannelShouldReturnEmptyOptional(TestConfigurator configurator) throws Exception { configurator.mockAndWhenChannel(c).thenReturn(null); configurator.mockAndWhenOptional(c).thenCallRealMethod(); - Optional optional = configurator.open(c); - assertFalse(optional.isPresent()); - optional.get(); + Assertions.assertThatThrownBy(() -> { + Optional optional = configurator.open(c); + assertFalse(optional.isPresent()); + optional.get(); + }).isInstanceOf(NoSuchElementException.class); } - @Test(expected = IOException.class) - public void openChannelShouldPropagateIoException() throws Exception { + @ParameterizedTest + @MethodSource("configurators") + public void openChannelShouldPropagateIoException(TestConfigurator configurator) throws Exception { configurator.mockAndWhenChannel(c).thenThrow(IOException.class); configurator.mockAndWhenOptional(c).thenCallRealMethod(); - configurator.open(c); + Assertions.assertThatThrownBy(() -> configurator.open(c)).isInstanceOf(IOException.class); } interface TestConfigurator { diff --git a/src/test/java/com/rabbitmq/client/test/DefaultRetryHandlerTest.java b/src/test/java/com/rabbitmq/client/test/DefaultRetryHandlerTest.java index ae841b430b..363c7285c8 100644 --- a/src/test/java/com/rabbitmq/client/test/DefaultRetryHandlerTest.java +++ b/src/test/java/com/rabbitmq/client/test/DefaultRetryHandlerTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -23,9 +23,9 @@ import com.rabbitmq.client.impl.recovery.RecordedQueue; import com.rabbitmq.client.impl.recovery.RetryContext; import com.rabbitmq.client.impl.recovery.RetryHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.verification.VerificationMode; @@ -33,8 +33,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiPredicate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.intThat; @@ -75,12 +75,12 @@ public class DefaultRetryHandlerTest { AutoCloseable mocks; - @Before + @BeforeEach public void init() { mocks = openMocks(this); } - @After + @AfterEach public void tearDown() throws Exception { mocks.close(); } diff --git a/src/test/java/com/rabbitmq/client/test/DnsRecordIpAddressResolverTests.java b/src/test/java/com/rabbitmq/client/test/DnsRecordIpAddressResolverTests.java index 5c38d5c8da..c339bf34e8 100644 --- a/src/test/java/com/rabbitmq/client/test/DnsRecordIpAddressResolverTests.java +++ b/src/test/java/com/rabbitmq/client/test/DnsRecordIpAddressResolverTests.java @@ -3,13 +3,13 @@ import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DnsRecordIpAddressResolver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.UnknownHostException; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * diff --git a/src/test/java/com/rabbitmq/client/test/DnsSrvRecordAddressResolverTest.java b/src/test/java/com/rabbitmq/client/test/DnsSrvRecordAddressResolverTest.java index 4950cc2323..839fb16fe4 100644 --- a/src/test/java/com/rabbitmq/client/test/DnsSrvRecordAddressResolverTest.java +++ b/src/test/java/com/rabbitmq/client/test/DnsSrvRecordAddressResolverTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,7 @@ import com.rabbitmq.client.Address; import com.rabbitmq.client.DnsSrvRecordAddressResolver; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; diff --git a/src/test/java/com/rabbitmq/client/test/FrameBuilderTest.java b/src/test/java/com/rabbitmq/client/test/FrameBuilderTest.java index 38fd654f3f..5c227ae1c6 100644 --- a/src/test/java/com/rabbitmq/client/test/FrameBuilderTest.java +++ b/src/test/java/com/rabbitmq/client/test/FrameBuilderTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,10 +19,11 @@ import com.rabbitmq.client.MalformedFrameException; import com.rabbitmq.client.impl.Frame; import com.rabbitmq.client.impl.nio.FrameBuilder; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.MockitoAnnotations; import java.io.IOException; import java.nio.ByteBuffer; @@ -34,7 +35,6 @@ /** * */ -@RunWith(MockitoJUnitRunner.class) public class FrameBuilderTest { @Mock @@ -44,10 +44,22 @@ public class FrameBuilderTest { FrameBuilder builder; + AutoCloseable mocks; + + @BeforeEach + void init() { + this.mocks = MockitoAnnotations.openMocks(this); + } + + @AfterEach + void tearDown() throws Exception { + mocks.close(); + } + @Test public void buildFrameInOneGo() throws IOException { buffer = ByteBuffer.wrap(new byte[] { 1, 0, 0, 0, 0, 0, 3, 1, 2, 3, end() }); - builder = new FrameBuilder(channel, buffer); + builder = new FrameBuilder(channel, buffer, Integer.MAX_VALUE); Frame frame = builder.readFrame(); assertThat(frame).isNotNull(); assertThat(frame.type).isEqualTo(1); @@ -66,7 +78,7 @@ public void buildFramesInOneGo() throws IOException { } } buffer = ByteBuffer.wrap(frames); - builder = new FrameBuilder(channel, buffer); + builder = new FrameBuilder(channel, buffer, Integer.MAX_VALUE); int frameCount = 0; Frame frame; while ((frame = builder.readFrame()) != null) { @@ -82,7 +94,7 @@ public void buildFramesInOneGo() throws IOException { @Test public void buildFrameInSeveralCalls() throws IOException { buffer = ByteBuffer.wrap(new byte[] { 1, 0, 0, 0, 0, 0, 3, 1, 2 }); - builder = new FrameBuilder(channel, buffer); + builder = new FrameBuilder(channel, buffer, Integer.MAX_VALUE); Frame frame = builder.readFrame(); assertThat(frame).isNull(); @@ -119,7 +131,7 @@ public void protocolMismatchHeader() throws IOException { }; for (int i = 0; i < buffers.length; i++) { - builder = new FrameBuilder(channel, buffers[i]); + builder = new FrameBuilder(channel, buffers[i], Integer.MAX_VALUE); try { builder.readFrame(); fail("protocol header not correct, exception should have been thrown"); diff --git a/src/test/java/com/rabbitmq/client/test/FrameTest.java b/src/test/java/com/rabbitmq/client/test/FrameTest.java index 26441a848b..fae132263b 100644 --- a/src/test/java/com/rabbitmq/client/test/FrameTest.java +++ b/src/test/java/com/rabbitmq/client/test/FrameTest.java @@ -3,17 +3,13 @@ import com.rabbitmq.client.AMQP; import com.rabbitmq.client.impl.Frame; import com.rabbitmq.client.impl.nio.ByteBufferOutputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; -import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Random; @@ -106,46 +102,6 @@ public void close() throws IOException { } } - private static class AccumulatorReadableByteChannel implements ReadableByteChannel { - - private List bytesOfFrames = new LinkedList(); - - @Override - public int read(ByteBuffer dst) throws IOException { - int remaining = dst.remaining(); - int read = 0; - if(remaining > 0) { - Iterator iterator = bytesOfFrames.iterator(); - while(iterator.hasNext() && read < remaining) { - dst.put(iterator.next()); - iterator.remove(); - read++; - } - } - return read; - } - - @Override - public boolean isOpen() { - return false; - } - - @Override - public void close() throws IOException { - - } - - void add(Frame frame) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(frame.size()); - DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream); - frame.writeTo(outputStream); - outputStream.flush(); - for (byte b : byteArrayOutputStream.toByteArray()) { - bytesOfFrames.add(b); - } - } - } - public static void drain(WritableByteChannel channel, ByteBuffer buffer) throws IOException { buffer.flip(); while(buffer.hasRemaining() && channel.write(buffer) != -1); diff --git a/src/test/java/com/rabbitmq/client/test/GeneratedClassesTest.java b/src/test/java/com/rabbitmq/client/test/GeneratedClassesTest.java index 78919bbca6..d8b139e7d7 100644 --- a/src/test/java/com/rabbitmq/client/test/GeneratedClassesTest.java +++ b/src/test/java/com/rabbitmq/client/test/GeneratedClassesTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,14 +17,14 @@ import com.rabbitmq.client.AMQP; import com.rabbitmq.client.impl.AMQImpl; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Calendar; import java.util.Date; import static java.util.Collections.singletonMap; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * diff --git a/src/test/java/com/rabbitmq/client/test/JSONReadWriteTest.java b/src/test/java/com/rabbitmq/client/test/JSONReadWriteTest.java index 3c71951aab..8aed35fb80 100644 --- a/src/test/java/com/rabbitmq/client/test/JSONReadWriteTest.java +++ b/src/test/java/com/rabbitmq/client/test/JSONReadWriteTest.java @@ -16,16 +16,17 @@ package com.rabbitmq.client.test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import com.rabbitmq.tools.json.JSONReader; import com.rabbitmq.tools.json.JSONWriter; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; public class JSONReadWriteTest { - @Test public void readWriteSimple() throws Exception { + @Test + public void readWriteSimple() throws Exception { Object myRet; String myJson; diff --git a/src/test/java/com/rabbitmq/client/test/JavaNioTest.java b/src/test/java/com/rabbitmq/client/test/JavaNioTest.java index 0d143e86e8..925c31ed55 100644 --- a/src/test/java/com/rabbitmq/client/test/JavaNioTest.java +++ b/src/test/java/com/rabbitmq/client/test/JavaNioTest.java @@ -5,9 +5,9 @@ import com.rabbitmq.client.impl.nio.DefaultByteBufferFactory; import com.rabbitmq.client.impl.nio.NioParams; import org.assertj.core.api.Condition; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.ByteBuffer; @@ -16,8 +16,8 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -28,14 +28,14 @@ public class JavaNioTest { private Connection testConnection; - @Before + @BeforeEach public void init() throws Exception { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.useNio(); testConnection = connectionFactory.newConnection(); } - @After + @AfterEach public void tearDown() throws Exception { if (testConnection != null) { testConnection.createChannel().queueDelete(QUEUE); @@ -52,7 +52,7 @@ public void connection() throws Exception { try { connection = basicGetBasicConsume(connectionFactory, "nio.queue", latch); boolean messagesReceived = latch.await(5, TimeUnit.SECONDS); - assertTrue("Message has not been received", messagesReceived); + assertTrue(messagesReceived, "Message has not been received"); } finally { safeClose(connection); } @@ -71,7 +71,7 @@ public void twoConnections() throws IOException, TimeoutException, InterruptedEx connection2 = basicGetBasicConsume(connectionFactory, "nio.queue.2", latch); boolean messagesReceived = latch.await(5, TimeUnit.SECONDS); - assertTrue("Messages have not been received", messagesReceived); + assertTrue(messagesReceived, "Messages have not been received"); } finally { safeClose(connection1); safeClose(connection2); @@ -91,7 +91,7 @@ public void twoConnectionsWithNioExecutor() throws IOException, TimeoutException connection2 = basicGetBasicConsume(connectionFactory, "nio.queue.2", latch); boolean messagesReceived = latch.await(5, TimeUnit.SECONDS); - assertTrue("Messages have not been received", messagesReceived); + assertTrue(messagesReceived, "Messages have not been received"); } finally { safeClose(connection1); safeClose(connection2); @@ -114,7 +114,7 @@ public void shutdownCompleted(ShutdownSignalException cause) { } }); safeClose(connection); - assertTrue("Shutdown listener should have been called", latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS), "Shutdown listener should have been called"); } finally { safeClose(connection); } @@ -194,7 +194,7 @@ public void customWriteQueue() throws Exception { private void sendAndVerifyMessage(Connection connection, int size) throws Exception { CountDownLatch latch = new CountDownLatch(1); boolean messageReceived = basicGetBasicConsume(connection, QUEUE, latch, size); - assertTrue("Message has not been received", messageReceived); + assertTrue(messageReceived, "Message has not been received"); } private Connection basicGetBasicConsume(ConnectionFactory connectionFactory, String queue, final CountDownLatch latch) diff --git a/src/test/java/com/rabbitmq/client/test/LambdaCallbackTest.java b/src/test/java/com/rabbitmq/client/test/LambdaCallbackTest.java index 0f30f4f83a..68390b0631 100644 --- a/src/test/java/com/rabbitmq/client/test/LambdaCallbackTest.java +++ b/src/test/java/com/rabbitmq/client/test/LambdaCallbackTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2017-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,7 @@ import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.UUID; @@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class LambdaCallbackTest extends BrokerTestCase { @@ -53,7 +53,7 @@ protected void releaseResources() throws IOException { Channel channel = connection.createChannel(); channel.addShutdownListener(cause -> latch.countDown()); } - assertTrue("Connection closed, shutdown listeners should have been called", latch.await(1, TimeUnit.SECONDS)); + assertTrue(latch.await(1, TimeUnit.SECONDS), "Connection closed, shutdown listeners should have been called"); } @Test public void confirmListener() throws Exception { @@ -64,14 +64,14 @@ protected void releaseResources() throws IOException { (deliveryTag, multiple) -> {} ); channel.basicPublish("", "whatever", null, "dummy".getBytes()); - assertTrue("Should have received publisher confirm", latch.await(1, TimeUnit.SECONDS)); + assertTrue(latch.await(1, TimeUnit.SECONDS), "Should have received publisher confirm"); } @Test public void returnListener() throws Exception { CountDownLatch latch = new CountDownLatch(1); channel.addReturnListener(returnMessage -> latch.countDown()); channel.basicPublish("", "notlikelytoexist", true, null, "dummy".getBytes()); - assertTrue("Should have received returned message", latch.await(1, TimeUnit.SECONDS)); + assertTrue(latch.await(1, TimeUnit.SECONDS), "Should have received returned message"); } @Test public void blockedListener() throws Exception { @@ -90,7 +90,7 @@ protected void releaseResources() throws IOException { block(); Channel ch = connection.createChannel(); ch.basicPublish("", "", null, "dummy".getBytes()); - assertTrue("Should have been blocked and unblocked", latch.await(10, TimeUnit.SECONDS)); + assertTrue(latch.await(10, TimeUnit.SECONDS), "Should have been blocked and unblocked"); } } @@ -104,9 +104,9 @@ protected void releaseResources() throws IOException { consumerTag -> cancelLatch.countDown() ); this.channel.basicPublish("", queue, null, "dummy".getBytes()); - assertTrue("deliver callback should have been called", consumingLatch.await(1, TimeUnit.SECONDS)); + assertTrue(consumingLatch.await(1, TimeUnit.SECONDS), "deliver callback should have been called"); this.channel.queueDelete(queue); - assertTrue("cancel callback should have been called", cancelLatch.await(1, TimeUnit.SECONDS)); + assertTrue(cancelLatch.await(1, TimeUnit.SECONDS), "cancel callback should have been called"); } } @@ -120,9 +120,9 @@ protected void releaseResources() throws IOException { (consumerTag, sig) -> shutdownLatch.countDown() ); this.channel.basicPublish("", queue, null, "dummy".getBytes()); - assertTrue("deliver callback should have been called", consumingLatch.await(1, TimeUnit.SECONDS)); + assertTrue(consumingLatch.await(1, TimeUnit.SECONDS), "deliver callback should have been called"); } - assertTrue("shutdown callback should have been called", shutdownLatch.await(1, TimeUnit.SECONDS)); + assertTrue(shutdownLatch.await(1, TimeUnit.SECONDS), "shutdown callback should have been called"); } @Test public void basicConsumeCancelDeliverShutdown() throws Exception { @@ -138,9 +138,9 @@ protected void releaseResources() throws IOException { (consumerTag, sig) -> shutdownLatch.countDown() ); this.channel.basicPublish("", queue, null, "dummy".getBytes()); - assertTrue("deliver callback should have been called", consumingLatch.await(1, TimeUnit.SECONDS)); + assertTrue(consumingLatch.await(1, TimeUnit.SECONDS), "deliver callback should have been called"); } - assertTrue("shutdown callback should have been called", shutdownLatch.await(1, TimeUnit.SECONDS)); + assertTrue(shutdownLatch.await(1, TimeUnit.SECONDS), "shutdown callback should have been called"); } } diff --git a/src/test/java/com/rabbitmq/client/test/LongStringTest.java b/src/test/java/com/rabbitmq/client/test/LongStringTest.java index 7c711b4fe4..82c6053116 100644 --- a/src/test/java/com/rabbitmq/client/test/LongStringTest.java +++ b/src/test/java/com/rabbitmq/client/test/LongStringTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,11 +17,11 @@ import com.rabbitmq.client.LongString; import com.rabbitmq.client.impl.LongStringHelper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class LongStringTest { diff --git a/src/test/java/com/rabbitmq/client/test/MaxInboundMessageSizeTest.java b/src/test/java/com/rabbitmq/client/test/MaxInboundMessageSizeTest.java new file mode 100644 index 0000000000..da534d9c5f --- /dev/null +++ b/src/test/java/com/rabbitmq/client/test/MaxInboundMessageSizeTest.java @@ -0,0 +1,97 @@ +// Copyright (c) 2023 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client.test; + +import static com.rabbitmq.client.test.TestUtils.LatchConditions.completed; +import static org.assertj.core.api.Assertions.assertThat; + +import com.rabbitmq.client.*; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +public class MaxInboundMessageSizeTest extends BrokerTestCase { + + String q; + + private static void safeClose(Connection c) { + try { + c.close(); + } catch (Exception e) { + // OK + } + } + + @Override + protected void createResources() throws IOException, TimeoutException { + q = generateQueueName(); + declareTransientQueue(q); + super.createResources(); + } + + @CsvSource({ + "20000,5000,true", + "20000,100000,true", + "20000,5000,false", + "20000,100000,false", + }) + @ParameterizedTest + void maxInboundMessageSizeMustBeEnforced(int maxMessageSize, int frameMax, boolean basicGet) + throws Exception { + ConnectionFactory cf = newConnectionFactory(); + cf.setMaxInboundMessageBodySize(maxMessageSize); + cf.setRequestedFrameMax(frameMax); + Connection c = cf.newConnection(); + try { + Channel ch = c.createChannel(); + ch.confirmSelect(); + byte[] body = new byte[maxMessageSize * 2]; + ch.basicPublish("", q, null, body); + ch.waitForConfirmsOrDie(); + AtomicReference exception = new AtomicReference<>(); + CountDownLatch errorLatch = new CountDownLatch(1); + ch.addShutdownListener( + cause -> { + exception.set(cause.getCause()); + errorLatch.countDown(); + }); + if (basicGet) { + try { + ch.basicGet(q, true); + } catch (Exception e) { + // OK for basicGet + } + } else { + ch.basicConsume(q, new DefaultConsumer(ch)); + } + assertThat(errorLatch).is(completed()); + assertThat(exception.get()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Message body is too large"); + } finally { + safeClose(c); + } + } + + @Override + protected void releaseResources() throws IOException { + deleteQueue(q); + super.releaseResources(); + } +} diff --git a/src/test/java/com/rabbitmq/client/test/MetricsCollectorTest.java b/src/test/java/com/rabbitmq/client/test/MetricsCollectorTest.java index 9c18b2ac1f..2286f6611a 100644 --- a/src/test/java/com/rabbitmq/client/test/MetricsCollectorTest.java +++ b/src/test/java/com/rabbitmq/client/test/MetricsCollectorTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,13 +20,20 @@ import com.rabbitmq.client.MetricsCollector; import com.rabbitmq.client.impl.AbstractMetricsCollector; import com.rabbitmq.client.impl.MicrometerMetricsCollector; +import com.rabbitmq.client.impl.OpenTelemetryMetricsCollector; import com.rabbitmq.client.impl.StandardMetricsCollector; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.testing.junit4.OpenTelemetryRule; +import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; @@ -35,22 +42,27 @@ /** * */ -@RunWith(Parameterized.class) public class MetricsCollectorTest { - @Parameterized.Parameters + @RegisterExtension + static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); + public static Object[] data() { // need to resort to a factory, as this method is called only once // if creating the collector instance, it's reused across the test methods // and this doesn't work (it cannot be reset) - return new Object[] { new StandardMetricsCollectorFactory(), new MicrometerMetricsCollectorFactory() }; + return new Object[]{new StandardMetricsCollectorFactory(), new MicrometerMetricsCollectorFactory(), new OpenTelemetryMetricsCollectorFactory()}; } - @Parameterized.Parameter - public MetricsCollectorFactory factory; + @BeforeEach + public void reset() { + // reset metrics + otelTesting.clearMetrics(); + } - @Test - public void basicGetAndAck() { + @ParameterizedTest + @MethodSource("data") + public void basicGetAndAck(MetricsCollectorFactory factory) { AbstractMetricsCollector metrics = factory.create(); Connection connection = mock(Connection.class); when(connection.getId()).thenReturn("connection-1"); @@ -81,7 +93,9 @@ public void basicGetAndAck() { assertThat(acknowledgedMessages(metrics)).isEqualTo(1L+2L+1L); } - @Test public void basicConsumeAndAck() { + @ParameterizedTest + @MethodSource("data") + public void basicConsumeAndAck(MetricsCollectorFactory factory) { AbstractMetricsCollector metrics = factory.create(); Connection connection = mock(Connection.class); when(connection.getId()).thenReturn("connection-1"); @@ -120,7 +134,9 @@ public void basicGetAndAck() { assertThat(acknowledgedMessages(metrics)).isEqualTo(1L+2L+1L); } - @Test public void publishingAndPublishingFailures() { + @ParameterizedTest + @MethodSource("data") + public void publishingAndPublishingFailures(MetricsCollectorFactory factory) { AbstractMetricsCollector metrics = factory.create(); Channel channel = mock(Channel.class); @@ -148,7 +164,9 @@ public void basicGetAndAck() { assertThat(publishedMessages(metrics)).isEqualTo(2L); } - @Test public void publishingAcknowledgements() { + @ParameterizedTest + @MethodSource("data") + public void publishingAcknowledgements(MetricsCollectorFactory factory) { long anyDeliveryTag = 123L; AbstractMetricsCollector metrics = factory.create(); Channel channel = mock(Channel.class); @@ -168,7 +186,9 @@ public void basicGetAndAck() { assertThat(publishAck(metrics)).isEqualTo(2); } - @Test public void publishingNotAcknowledgements() { + @ParameterizedTest + @MethodSource("data") + public void publishingNotAcknowledgements(MetricsCollectorFactory factory) { long anyDeliveryTag = 123L; AbstractMetricsCollector metrics = factory.create(); Channel channel = mock(Channel.class); @@ -188,7 +208,9 @@ public void basicGetAndAck() { assertThat(publishNack(metrics)).isEqualTo(2L); } - @Test public void publishingUnrouted() { + @ParameterizedTest + @MethodSource("data") + public void publishingUnrouted(MetricsCollectorFactory factory) { AbstractMetricsCollector metrics = factory.create(); Channel channel = mock(Channel.class); // begins with no messages not-acknowledged @@ -204,7 +226,9 @@ public void basicGetAndAck() { assertThat(publishUnrouted(metrics)).isEqualTo(2L); } - @Test public void cleanStaleState() { + @ParameterizedTest + @MethodSource("data") + public void cleanStaleState(MetricsCollectorFactory factory) { AbstractMetricsCollector metrics = factory.create(); Connection openConnection = mock(Connection.class); when(openConnection.getId()).thenReturn("connection-1"); @@ -248,73 +272,109 @@ public void basicGetAndAck() { long publishAck(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getPublishAcknowledgedMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getAckedPublishedMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getAckedPublishedMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.acknowledged_published"); } } long publishNack(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getPublishNotAcknowledgedMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getNackedPublishedMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getNackedPublishedMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.not_acknowledged_published"); } } long publishUnrouted(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getPublishUnroutedMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getUnroutedPublishedMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getUnroutedPublishedMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.unrouted_published"); } } long publishedMessages(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getPublishedMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getPublishedMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getPublishedMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.published"); } } long failedToPublishMessages(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getFailedToPublishMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getFailedToPublishMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getFailedToPublishMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.failed_to_publish"); } } long consumedMessages(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getConsumedMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getConsumedMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getConsumedMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.consumed"); } } long acknowledgedMessages(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getAcknowledgedMessages().getCount(); - } else { - return (long) ((MicrometerMetricsCollector) metrics).getAcknowledgedMessages().count(); + } + else if (metrics instanceof MicrometerMetricsCollector) { + return (long)((MicrometerMetricsCollector) metrics).getAcknowledgedMessages().count(); + } + else { + return getOpenTelemetryCounterMeterValue("rabbitmq.acknowledged"); } } long connections(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getConnections().getCount(); - } else { + } + else if (metrics instanceof MicrometerMetricsCollector) { return ((MicrometerMetricsCollector) metrics).getConnections().get(); } + else { + return ((OpenTelemetryMetricsCollector)metrics).getConnections().get(); + } } long channels(MetricsCollector metrics) { if (metrics instanceof StandardMetricsCollector) { return ((StandardMetricsCollector) metrics).getChannels().getCount(); - } else { + } + else if (metrics instanceof MicrometerMetricsCollector) { return ((MicrometerMetricsCollector) metrics).getChannels().get(); } + else { + return ((OpenTelemetryMetricsCollector)metrics).getChannels().get(); + } } interface MetricsCollectorFactory { @@ -335,4 +395,23 @@ public AbstractMetricsCollector create() { } } + static class OpenTelemetryMetricsCollectorFactory implements MetricsCollectorFactory { + @Override + public AbstractMetricsCollector create() { + return new OpenTelemetryMetricsCollector(otelTesting.getOpenTelemetry()); + } + } + + static long getOpenTelemetryCounterMeterValue(String name) { + // open telemetry metrics + List metrics = otelTesting.getMetrics(); + // metric value + return metrics.stream() + .filter(metric -> metric.getName().equals(name)) + .flatMap(metric -> metric.getData().getPoints().stream()) + .map(point -> (LongPointData)point) + .map(LongPointData::getValue) + .mapToLong(value -> value) + .sum(); + } } diff --git a/src/test/java/com/rabbitmq/client/test/MicrometerMetricsCollectorTest.java b/src/test/java/com/rabbitmq/client/test/MicrometerMetricsCollectorTest.java index 125d185160..16c7fc12df 100644 --- a/src/test/java/com/rabbitmq/client/test/MicrometerMetricsCollectorTest.java +++ b/src/test/java/com/rabbitmq/client/test/MicrometerMetricsCollectorTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,12 +15,14 @@ package com.rabbitmq.client.test; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import com.rabbitmq.client.impl.MicrometerMetricsCollector; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @@ -31,7 +33,7 @@ public class MicrometerMetricsCollectorTest { MicrometerMetricsCollector collector; - @Before + @BeforeEach public void init() { registry = new SimpleMeterRegistry(); } @@ -52,9 +54,10 @@ public void tags() { } } - @Test(expected = IllegalArgumentException.class) + @Test public void tagsMustBeKeyValuePairs() { - collector = new MicrometerMetricsCollector(registry, "rabbitmq", "uri"); + assertThatThrownBy(() -> new MicrometerMetricsCollector(registry, "rabbitmq", "uri")) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/src/test/java/com/rabbitmq/client/test/MultiThreadedChannel.java b/src/test/java/com/rabbitmq/client/test/MultiThreadedChannel.java index 93a2d1c837..7893ab056b 100644 --- a/src/test/java/com/rabbitmq/client/test/MultiThreadedChannel.java +++ b/src/test/java/com/rabbitmq/client/test/MultiThreadedChannel.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,7 @@ import java.util.concurrent.atomic.AtomicReference; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests whether a Channel is safe for multi-threaded access diff --git a/src/test/java/com/rabbitmq/client/test/NioDeadlockOnConnectionClosing.java b/src/test/java/com/rabbitmq/client/test/NioDeadlockOnConnectionClosing.java index 0f3984ade7..9ca7dd156a 100644 --- a/src/test/java/com/rabbitmq/client/test/NioDeadlockOnConnectionClosing.java +++ b/src/test/java/com/rabbitmq/client/test/NioDeadlockOnConnectionClosing.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -18,9 +18,9 @@ import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.impl.nio.NioParams; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +31,7 @@ import java.util.concurrent.TimeUnit; import static com.rabbitmq.client.test.TestUtils.closeAllConnectionsAndWaitForRecovery; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -44,7 +44,7 @@ public class NioDeadlockOnConnectionClosing { ConnectionFactory cf; List connections; - @Before + @BeforeEach public void setUp() { nioExecutorService = Executors.newFixedThreadPool(2); connectionShutdownExecutorService = Executors.newFixedThreadPool(2); @@ -60,7 +60,7 @@ public void setUp() { connections = new ArrayList<>(); } - @After + @AfterEach public void tearDown() throws Exception { for (Connection connection : connections) { try { diff --git a/src/test/java/com/rabbitmq/client/test/NoAutoRecoveryWhenTcpWindowIsFullTest.java b/src/test/java/com/rabbitmq/client/test/NoAutoRecoveryWhenTcpWindowIsFullTest.java index 247fdcfd57..ea0bf72c74 100644 --- a/src/test/java/com/rabbitmq/client/test/NoAutoRecoveryWhenTcpWindowIsFullTest.java +++ b/src/test/java/com/rabbitmq/client/test/NoAutoRecoveryWhenTcpWindowIsFullTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -27,10 +27,10 @@ import com.rabbitmq.client.impl.nio.NioParams; import com.rabbitmq.client.impl.recovery.AutorecoveringChannel; import com.rabbitmq.client.impl.recovery.AutorecoveringConnection; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import com.rabbitmq.client.test.TestUtils.DisabledIfBrokerRunningOnDocker; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.Socket; @@ -42,7 +42,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; -import org.junit.rules.TestRule; import static org.assertj.core.api.Assertions.assertThat; @@ -66,11 +65,9 @@ * to the socket fails. *

*/ +@DisabledIfBrokerRunningOnDocker public class NoAutoRecoveryWhenTcpWindowIsFullTest { - @ClassRule - public static TestRule brokerOnDockerTestRule = TestUtils.brokerIsNotRunningOnDocker(); - private static final int NUM_MESSAGES_TO_PRODUCE = 50000; private static final int MESSAGE_PROCESSING_TIME_MS = 3000; private static final byte[] MESSAGE_CONTENT = ("MESSAGE CONTENT " + NUM_MESSAGES_TO_PRODUCE).getBytes(); @@ -83,7 +80,7 @@ public class NoAutoRecoveryWhenTcpWindowIsFullTest { private CountDownLatch consumerOkLatch; - @Before + @BeforeEach public void setUp() throws Exception { // we need several threads to publish, dispatch deliveries, handle RPC responses, etc. executorService = Executors.newFixedThreadPool(10); @@ -123,7 +120,7 @@ public void configure(Socket socket) throws IOException { consumerOkLatch = new CountDownLatch(2); } - @After + @AfterEach public void tearDown() throws IOException { closeConnectionIfOpen(consumingConnection); closeConnectionIfOpen(producingConnection); diff --git a/src/test/java/com/rabbitmq/client/test/PropertyFileInitialisationTest.java b/src/test/java/com/rabbitmq/client/test/PropertyFileInitialisationTest.java index 40138a26d6..24d3f808d8 100644 --- a/src/test/java/com/rabbitmq/client/test/PropertyFileInitialisationTest.java +++ b/src/test/java/com/rabbitmq/client/test/PropertyFileInitialisationTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,7 @@ import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.ConnectionFactoryConfigurator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.net.ssl.SSLContext; import java.io.FileReader; diff --git a/src/test/java/com/rabbitmq/client/test/QueueingConsumerTests.java b/src/test/java/com/rabbitmq/client/test/QueueingConsumerTests.java index ba9d72e47b..4a4793952f 100644 --- a/src/test/java/com/rabbitmq/client/test/QueueingConsumerTests.java +++ b/src/test/java/com/rabbitmq/client/test/QueueingConsumerTests.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,10 +15,10 @@ package com.rabbitmq.client.test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import com.rabbitmq.client.ConsumerCancelledException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; diff --git a/src/test/java/com/rabbitmq/client/test/RecoveryAwareAMQConnectionFactoryTest.java b/src/test/java/com/rabbitmq/client/test/RecoveryAwareAMQConnectionFactoryTest.java index 785b58ec53..2b40553778 100644 --- a/src/test/java/com/rabbitmq/client/test/RecoveryAwareAMQConnectionFactoryTest.java +++ b/src/test/java/com/rabbitmq/client/test/RecoveryAwareAMQConnectionFactoryTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -24,7 +24,7 @@ import com.rabbitmq.client.impl.FrameHandlerFactory; import com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnection; import com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; @@ -32,7 +32,7 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.mockito.Mockito.*; public class RecoveryAwareAMQConnectionFactoryTest { diff --git a/src/test/java/com/rabbitmq/client/test/RecoveryDelayHandlerTest.java b/src/test/java/com/rabbitmq/client/test/RecoveryDelayHandlerTest.java index be9958b487..035b96191d 100644 --- a/src/test/java/com/rabbitmq/client/test/RecoveryDelayHandlerTest.java +++ b/src/test/java/com/rabbitmq/client/test/RecoveryDelayHandlerTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,8 @@ package com.rabbitmq.client.test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.Collections; @@ -24,7 +25,7 @@ import com.rabbitmq.client.RecoveryDelayHandler.DefaultRecoveryDelayHandler; import com.rabbitmq.client.RecoveryDelayHandler.ExponentialBackoffDelayHandler; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class RecoveryDelayHandlerTest { @@ -61,13 +62,15 @@ public void testExponentialBackoffDelayHandlerSequence() { assertEquals(2, handler.getDelay(Integer.MAX_VALUE)); } - @Test(expected=IllegalArgumentException.class) + @Test public void testExponentialBackoffDelayHandlerWithNullSequence() { - new ExponentialBackoffDelayHandler(null); + assertThatThrownBy(() -> new ExponentialBackoffDelayHandler(null)) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected=IllegalArgumentException.class) + @Test public void testExponentialBackoffDelayHandlerWithEmptySequence() { - new ExponentialBackoffDelayHandler(Collections.emptyList()); + assertThatThrownBy(() -> new ExponentialBackoffDelayHandler(Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/src/test/java/com/rabbitmq/client/test/RefreshCredentialsTest.java b/src/test/java/com/rabbitmq/client/test/RefreshCredentialsTest.java index 0a0100cbc6..8e32dbc6c3 100644 --- a/src/test/java/com/rabbitmq/client/test/RefreshCredentialsTest.java +++ b/src/test/java/com/rabbitmq/client/test/RefreshCredentialsTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,10 +20,10 @@ import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.impl.DefaultCredentialsRefreshService; import com.rabbitmq.client.impl.RefreshProtectedCredentialsProvider; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TestRule; +import com.rabbitmq.client.test.TestUtils.BrokerVersion; +import com.rabbitmq.client.test.TestUtils.BrokerVersionAtLeast; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; @@ -33,13 +33,12 @@ import static org.assertj.core.api.Assertions.assertThat; +@BrokerVersionAtLeast(BrokerVersion.RABBITMQ_3_8) public class RefreshCredentialsTest { - @ClassRule - public static TestRule brokerVersionTestRule = TestUtils.atLeast38(); DefaultCredentialsRefreshService refreshService; - @Before + @BeforeEach public void tearDown() { if (refreshService != null) { refreshService.close(); diff --git a/src/test/java/com/rabbitmq/client/test/RequiredPropertiesSuite.java b/src/test/java/com/rabbitmq/client/test/RequiredPropertiesSuite.java index b97a0b0af6..f0040e43ab 100644 --- a/src/test/java/com/rabbitmq/client/test/RequiredPropertiesSuite.java +++ b/src/test/java/com/rabbitmq/client/test/RequiredPropertiesSuite.java @@ -1,17 +1,18 @@ package com.rabbitmq.client.test; -import org.junit.runner.Runner; -import org.junit.runners.Suite; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; import java.util.ArrayList; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * */ -public class RequiredPropertiesSuite extends Suite { +public class RequiredPropertiesSuite { //extends Suite { + +/* + private static final Logger LOGGER = LoggerFactory.getLogger(RequiredPropertiesSuite.class); public RequiredPropertiesSuite(Class klass, RunnerBuilder builder) throws InitializationError { super(klass, builder); @@ -41,4 +42,12 @@ protected List getChildren() { return super.getChildren(); } } + + @Override + protected void runChild(Runner runner, RunNotifier notifier) { + LOGGER.info("Running test {}", runner.getDescription().getDisplayName()); + super.runChild(runner, notifier); + } + + */ } diff --git a/src/test/java/com/rabbitmq/client/test/RpcTest.java b/src/test/java/com/rabbitmq/client/test/RpcTest.java index 6180e557ec..5d95d0d448 100644 --- a/src/test/java/com/rabbitmq/client/test/RpcTest.java +++ b/src/test/java/com/rabbitmq/client/test/RpcTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2017-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -25,9 +25,9 @@ import com.rabbitmq.client.impl.recovery.TopologyRecoveryFilter; import com.rabbitmq.tools.Host; import org.assertj.core.api.Assertions; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.time.Duration; @@ -40,7 +40,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static com.rabbitmq.client.test.TestUtils.waitAtMost; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class RpcTest { @@ -49,7 +49,7 @@ public class RpcTest { String queue = "rpc.queue"; RpcServer rpcServer; - @Before + @BeforeEach public void init() throws Exception { clientConnection = TestUtils.connectionFactory().newConnection(); clientChannel = clientConnection.createChannel(); @@ -58,7 +58,7 @@ public void init() throws Exception { serverChannel.queueDeclare(queue, false, false, false, null); } - @After + @AfterEach public void tearDown() throws Exception { if (rpcServer != null) { rpcServer.terminateMainloop(); @@ -137,7 +137,11 @@ public void rpcUnroutableWithMandatoryFlagShouldThrowUnroutableException() throw assertEquals(noWhereRoutingKey, e.getReturnMessage().getRoutingKey()); assertEquals(content, new String(e.getReturnMessage().getBody())); } - client.close(); + try { + client.close(); + } catch (IOException e) { + // OK + } } @Test @@ -237,7 +241,7 @@ public void handleRecoveryStarted(Recoverable recoverable) { } }); Host.closeConnection((NetworkConnection) connection); - assertTrue("Connection should have recovered by now", recoveryLatch.await(10, TimeUnit.SECONDS)); + assertTrue(recoveryLatch.await(10, TimeUnit.SECONDS), "Connection should have recovered by now"); client = new RpcClient(new RpcClientParams() .channel(channel).exchange("").routingKey(queue).timeout(1000)); response = client.doCall(null, "hello".getBytes()); @@ -285,7 +289,7 @@ public void handleRecoveryStarted(Recoverable recoverable) { } }); Host.closeConnection((NetworkConnection) connection); - assertTrue("Connection should have recovered by now", recoveryLatch.await(10, TimeUnit.SECONDS)); + assertTrue(recoveryLatch.await(10, TimeUnit.SECONDS), "Connection should have recovered by now"); try { new RpcClient(new RpcClientParams() .channel(channel).exchange("").routingKey(queue).timeout(1000)); diff --git a/src/test/java/com/rabbitmq/client/test/RpcTopologyRecordingTest.java b/src/test/java/com/rabbitmq/client/test/RpcTopologyRecordingTest.java index 3769218fd7..249eeb3f1b 100644 --- a/src/test/java/com/rabbitmq/client/test/RpcTopologyRecordingTest.java +++ b/src/test/java/com/rabbitmq/client/test/RpcTopologyRecordingTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,9 +17,6 @@ import com.rabbitmq.client.*; import com.rabbitmq.client.impl.AMQImpl; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import java.io.IOException; import java.util.UUID; @@ -27,20 +24,18 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static com.rabbitmq.client.test.TestUtils.closeAndWaitForRecovery; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(Parameterized.class) public class RpcTopologyRecordingTest extends BrokerTestCase { - @Parameterized.Parameter - public RpcCall rpcCall; String exchange, queue, routingKey; String exchange2, queue2, routingKey2; - @Parameterized.Parameters public static Object[] data() { return new Object[]{ (RpcCall) (channel, method) -> channel.asyncCompletableRpc(method).get(5, TimeUnit.SECONDS), @@ -73,9 +68,10 @@ protected void releaseResources() throws IOException { channel.exchangeDelete(exchange2); } - @Test - public void topologyRecovery() throws Exception { - createTopology(); + @ParameterizedTest + @MethodSource("data") + public void topologyRecovery(RpcCall rpcCall) throws Exception { + createTopology(rpcCall); AtomicReference latch = new AtomicReference<>(new CountDownLatch(2)); DeliverCallback countDown = (ctag, message) -> latch.get().countDown(); @@ -98,9 +94,10 @@ public void topologyRecovery() throws Exception { assertTrue(latch.get().await(5, TimeUnit.SECONDS)); } - @Test - public void deletionAreProperlyRecorded() throws Exception { - createTopology(); + @ParameterizedTest + @MethodSource("data") + public void deletionAreProperlyRecorded(RpcCall rpcCall) throws Exception { + createTopology(rpcCall); AtomicReference latch = new AtomicReference<>(new CountDownLatch(2)); DeliverCallback countDown = (ctag, message) -> latch.get().countDown(); @@ -151,9 +148,10 @@ boolean exchangeExists(String exchange) throws TimeoutException { } } - @Test - public void bindingDeletionAreProperlyRecorded() throws Exception { - createTopology(); + @ParameterizedTest + @MethodSource("data") + public void bindingDeletionAreProperlyRecorded(RpcCall rpcCall) throws Exception { + createTopology(rpcCall); AtomicReference latch = new AtomicReference<>(new CountDownLatch(2)); DeliverCallback countDown = (ctag, message) -> latch.get().countDown(); @@ -167,7 +165,7 @@ public void bindingDeletionAreProperlyRecorded() throws Exception { assertTrue(latch.get().await(5, TimeUnit.SECONDS)); - unbind(); + unbind(rpcCall); latch.set(new CountDownLatch(2)); @@ -178,9 +176,9 @@ public void bindingDeletionAreProperlyRecorded() throws Exception { assertFalse(latch.get().await(2, TimeUnit.SECONDS)); } - private void createTopology() throws Exception { - createAndBind(exchange, queue, routingKey); - createAndBind(exchange2, queue2, routingKey2); + private void createTopology(RpcCall rpcCall) throws Exception { + createAndBind(rpcCall, exchange, queue, routingKey); + createAndBind(rpcCall, exchange2, queue2, routingKey2); rpcCall.call(channel, new AMQImpl.Exchange.Bind.Builder() .source(exchange) .destination(exchange2) @@ -189,7 +187,7 @@ private void createTopology() throws Exception { .build()); } - private void createAndBind(String e, String q, String rk) throws Exception { + private void createAndBind(RpcCall rpcCall, String e, String q, String rk) throws Exception { rpcCall.call(channel, new AMQImpl.Queue.Declare.Builder() .queue(q) .durable(false) @@ -212,7 +210,7 @@ private void createAndBind(String e, String q, String rk) throws Exception { .build()); } - private void unbind() throws Exception { + private void unbind(RpcCall rpcCall) throws Exception { rpcCall.call(channel, new AMQImpl.Queue.Unbind.Builder() .exchange(exchange) .queue(queue) diff --git a/src/test/java/com/rabbitmq/client/test/SharedThreadPoolTest.java b/src/test/java/com/rabbitmq/client/test/SharedThreadPoolTest.java index 747a2805e5..0e8317b987 100644 --- a/src/test/java/com/rabbitmq/client/test/SharedThreadPoolTest.java +++ b/src/test/java/com/rabbitmq/client/test/SharedThreadPoolTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,8 +15,8 @@ package com.rabbitmq.client.test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.ExecutorService; @@ -24,7 +24,7 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.Connection; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.impl.AMQConnection; diff --git a/src/test/java/com/rabbitmq/client/test/SslContextFactoryTest.java b/src/test/java/com/rabbitmq/client/test/SslContextFactoryTest.java index 585e74f7a8..69a3eee1e8 100644 --- a/src/test/java/com/rabbitmq/client/test/SslContextFactoryTest.java +++ b/src/test/java/com/rabbitmq/client/test/SslContextFactoryTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,7 +19,7 @@ import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.SslContextFactory; import com.rabbitmq.client.TrustEverythingTrustManager; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; @@ -32,7 +32,7 @@ import java.util.Map; import java.util.function.Supplier; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * diff --git a/src/test/java/com/rabbitmq/client/test/StrictExceptionHandlerTest.java b/src/test/java/com/rabbitmq/client/test/StrictExceptionHandlerTest.java index fbb3ad984b..c2a3f28aa9 100644 --- a/src/test/java/com/rabbitmq/client/test/StrictExceptionHandlerTest.java +++ b/src/test/java/com/rabbitmq/client/test/StrictExceptionHandlerTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -23,7 +23,7 @@ import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.impl.StrictExceptionHandler; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; diff --git a/src/test/java/com/rabbitmq/client/test/TableTest.java b/src/test/java/com/rabbitmq/client/test/TableTest.java index bb07a71f21..be808fa262 100644 --- a/src/test/java/com/rabbitmq/client/test/TableTest.java +++ b/src/test/java/com/rabbitmq/client/test/TableTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,9 @@ package com.rabbitmq.client.test; import com.rabbitmq.client.impl.*; -import org.junit.Test; +import java.sql.Timestamp; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.*; import java.math.BigDecimal; @@ -25,12 +27,12 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TableTest { - public byte [] marshal(Map table) + public byte [] marshal(Map table) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); @@ -59,10 +61,14 @@ public Date secondDate() return new Date((System.currentTimeMillis()/1000)*1000); } + private static Timestamp timestamp() { + return new Timestamp((System.currentTimeMillis()/1000)*1000); + } + @Test public void loop() throws IOException { - Map table = new HashMap(); + Map table = new HashMap<>(); table.put("a", 1); assertEquals(table, unmarshal(marshal(table))); @@ -77,5 +83,11 @@ public Date secondDate() table.put("e", -126); assertEquals(table, unmarshal(marshal(table))); + + Timestamp timestamp = timestamp(); + table.put("f", timestamp); + Map tableWithTimestampAsDate = new HashMap<>(table); + tableWithTimestampAsDate.put("f", new Date(timestamp.getTime())); + assertEquals(tableWithTimestampAsDate, unmarshal(marshal(table))); } } diff --git a/src/test/java/com/rabbitmq/client/test/TestUtils.java b/src/test/java/com/rabbitmq/client/test/TestUtils.java index e16bca6f40..ec495bcb83 100644 --- a/src/test/java/com/rabbitmq/client/test/TestUtils.java +++ b/src/test/java/com/rabbitmq/client/test/TestUtils.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,28 +19,31 @@ import com.rabbitmq.client.impl.NetworkConnection; import com.rabbitmq.client.impl.recovery.AutorecoveringConnection; import com.rabbitmq.tools.Host; +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.function.Function; import org.assertj.core.api.Assertions; -import org.junit.AssumptionViolatedException; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.assertj.core.api.Condition; +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; import org.slf4j.LoggerFactory; -import javax.net.ssl.SSLContext; import java.io.IOException; import java.net.ServerSocket; -import java.security.NoSuchAlgorithmException; import java.time.Duration; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import java.util.function.BooleanSupplier; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestUtils { @@ -56,9 +59,24 @@ public static ConnectionFactory connectionFactory() { return connectionFactory; } - public static void waitAtMost(Duration timeout, BooleanSupplier condition) { - if (condition.getAsBoolean()) { - return; + @FunctionalInterface + public interface CallableBooleanSupplier { + + boolean getAsBoolean() throws Exception; + + } + + public static void waitAtMost(CallableBooleanSupplier condition) { + waitAtMost(Duration.ofSeconds(10), condition); + } + + public static void waitAtMost(Duration timeout, CallableBooleanSupplier condition) { + try { + if (condition.getAsBoolean()) { + return; + } + } catch (Exception e) { + throw new RuntimeException(e); } int waitTime = 100; int waitedTime = 0; @@ -70,8 +88,12 @@ public static void waitAtMost(Duration timeout, BooleanSupplier condition) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } - if (condition.getAsBoolean()) { - return; + try { + if (condition.getAsBoolean()) { + return; + } + } catch (Exception e) { + throw new RuntimeException(e); } waitedTime += waitTime; } @@ -94,30 +116,6 @@ public static void abort(Connection connection) { } } - public static SSLContext getSSLContext() throws NoSuchAlgorithmException { - SSLContext c = null; - - // pick the first protocol available, preferring TLSv1.2, then TLSv1, - // falling back to SSLv3 if running on an ancient/crippled JDK - for (String proto : Arrays.asList("TLSv1.2", "TLSv1", "SSLv3")) { - try { - c = SSLContext.getInstance(proto); - return c; - } catch (NoSuchAlgorithmException x) { - // keep trying - } - } - throw new NoSuchAlgorithmException(); - } - - public static TestRule atLeast38() { - return new BrokerVersionTestRule("3.8.0"); - } - - public static TestRule brokerIsNotRunningOnDocker() { - return new BrokerIsNotOnDocker(); - } - public static boolean isVersion37orLater(Connection connection) { return atLeastVersion("3.7.0", connection); } @@ -126,12 +124,16 @@ public static boolean isVersion38orLater(Connection connection) { return atLeastVersion("3.8.0", connection); } + public static boolean isVersion310orLater(Connection connection) { + return atLeastVersion("3.10.0", connection); + } + private static boolean atLeastVersion(String expectedVersion, Connection connection) { - String currentVersion = null; + return atLeastVersion(expectedVersion, currentVersion(connection.getServerProperties().get("version").toString())); + } + + private static boolean atLeastVersion(String expectedVersion, String currentVersion) { try { - currentVersion = currentVersion( - connection.getServerProperties().get("version").toString() - ); return "0.0.0".equals(currentVersion) || versionCompare(currentVersion, expectedVersion) >= 0; } catch (RuntimeException e) { LoggerFactory.getLogger(TestUtils.class).warn("Unable to parse broker version {}", currentVersion, e); @@ -292,56 +294,215 @@ public static int randomNetworkPort() throws IOException { return port; } - private static class BrokerVersionTestRule implements TestRule { + @FunctionalInterface + public interface CallableFunction { - private final String version; + R apply(T t) throws Exception; - public BrokerVersionTestRule(String version) { - this.version = version; + } + + public static class LatchConditions { + + static Condition completed() { + return new Condition<>( + countDownLatch-> { + try { + return countDownLatch.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }, + "Latch did not complete in 10 seconds"); + } + + } + + public static boolean basicGetBasicConsume(Connection connection, String queue, final CountDownLatch latch, int msgSize) + throws Exception { + Channel channel = connection.createChannel(); + channel.queueDeclare(queue, false, true, false, null); + channel.queuePurge(queue); + + channel.basicPublish("", queue, null, new byte[msgSize]); + + String tag = channel.basicConsume(queue, false, new DefaultConsumer(channel) { + + @Override + public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { + getChannel().basicAck(envelope.getDeliveryTag(), false); + latch.countDown(); + } + }); + + boolean messageReceived = latch.await(20, TimeUnit.SECONDS); + + channel.basicCancel(tag); + + return messageReceived; + } + + /* + public static class DefaultTestSuite extends Suite { + + + public DefaultTestSuite(Class klass, RunnerBuilder builder) + throws InitializationError { + super(klass, builder); + } + + public DefaultTestSuite(RunnerBuilder builder, Class[] classes) + throws InitializationError { + super(builder, classes); + } + + protected DefaultTestSuite(Class klass, Class[] suiteClasses) + throws InitializationError { + super(klass, suiteClasses); + } + + protected DefaultTestSuite(RunnerBuilder builder, Class klass, Class[] suiteClasses) + throws InitializationError { + super(builder, klass, suiteClasses); } @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try (Connection c = TestUtils.connectionFactory().newConnection()) { - if (!TestUtils.atLeastVersion(version, c)) { - throw new AssumptionViolatedException("Broker version < " + version + ", skipping."); - } - } - base.evaluate(); - } - }; + protected void runChild(Runner runner, RunNotifier notifier) { + LOGGER.info("Running test {}", runner.getDescription().getDisplayName()); + super.runChild(runner, notifier); + } + + protected DefaultTestSuite(Class klass, List runners) + throws InitializationError { + super(klass, runners); + } + } + + */ + + public static void safeDelete(Connection connection, String queue) { + try { + Channel ch = connection.createChannel(); + ch.queueDelete(queue); + ch.close(); + } catch (Exception e) { + // OK } } - private static class BrokerIsNotOnDocker implements TestRule { + private static class BaseBrokerVersionAtLeastCondition implements + org.junit.jupiter.api.extension.ExecutionCondition { + + private final Function versionProvider; + private BaseBrokerVersionAtLeastCondition(Function versionProvider) { + this.versionProvider = versionProvider; + } @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - if (Host.isOnDocker()) { - throw new AssumptionViolatedException("Broker is running on Docker"); - } - } catch (Exception e) { - throw new AssumptionViolatedException("Could not check whether broker is running on Docker or not", e); - } - base.evaluate(); + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + if (!context.getTestMethod().isPresent()) { + return ConditionEvaluationResult.enabled("Apply only to methods"); + } + String expectedVersion = versionProvider.apply(context); + if (expectedVersion == null) { + return ConditionEvaluationResult.enabled("No broker version requirement"); + } else { + String brokerVersion = + context + .getRoot() + .getStore(Namespace.GLOBAL) + .getOrComputeIfAbsent( + "brokerVersion", + k -> { + try (Connection c = TestUtils.connectionFactory().newConnection()) { + return currentVersion( + c.getServerProperties().get("version").toString() + ); + } catch (Exception e) { + throw new RuntimeException(e); + } + }, + String.class); + + if (atLeastVersion(expectedVersion, brokerVersion)) { + return ConditionEvaluationResult.enabled( + "Broker version requirement met, expected " + + expectedVersion + + ", actual " + + brokerVersion); + } else { + return ConditionEvaluationResult.disabled( + "Broker version requirement not met, expected " + + expectedVersion + + ", actual " + + brokerVersion); } - }; + } } } - @FunctionalInterface - public interface CallableFunction { + private static class AnnotationBrokerVersionAtLeastCondition + extends BaseBrokerVersionAtLeastCondition { - R apply(T t) throws Exception; + private AnnotationBrokerVersionAtLeastCondition() { + super( + context -> { + BrokerVersionAtLeast annotation = + context.getElement().get().getAnnotation(BrokerVersionAtLeast.class); + return annotation == null ? null : annotation.value().toString(); + }); + } + } + + static class BrokerVersionAtLeast310Condition extends BaseBrokerVersionAtLeastCondition { + + private BrokerVersionAtLeast310Condition() { + super(context -> "3.10.0"); + } + } + + @Target({ElementType.TYPE, ElementType.METHOD}) + @Retention(RetentionPolicy.RUNTIME) + @Documented + @ExtendWith(AnnotationBrokerVersionAtLeastCondition.class) + public @interface BrokerVersionAtLeast { + + BrokerVersion value(); + } + + public enum BrokerVersion { + RABBITMQ_3_8("3.8.0"), + RABBITMQ_3_10("3.10.0"); + final String value; + + BrokerVersion(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } } + static class DisabledIfBrokerRunningOnDockerCondition implements + org.junit.jupiter.api.extension.ExecutionCondition { + + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + if (Host.isOnDocker()) { + return ConditionEvaluationResult.disabled("Broker running on Docker"); + } else { + return ConditionEvaluationResult.enabled("Broker not running on Docker"); + } + } + } + + @Target({ElementType.TYPE, ElementType.METHOD}) + @Retention(RetentionPolicy.RUNTIME) + @Documented + @ExtendWith(DisabledIfBrokerRunningOnDockerCondition.class) + @interface DisabledIfBrokerRunningOnDocker {} + } diff --git a/src/test/java/com/rabbitmq/client/test/TestUtilsTest.java b/src/test/java/com/rabbitmq/client/test/TestUtilsTest.java index b73e8033cc..897296938d 100644 --- a/src/test/java/com/rabbitmq/client/test/TestUtilsTest.java +++ b/src/test/java/com/rabbitmq/client/test/TestUtilsTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2017-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2017-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,7 +17,7 @@ import com.rabbitmq.client.Connection; import org.assertj.core.api.Assertions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; diff --git a/src/test/java/com/rabbitmq/client/test/TlsUtilsTest.java b/src/test/java/com/rabbitmq/client/test/TlsUtilsTest.java index f04d22dc1c..51a1b691e1 100644 --- a/src/test/java/com/rabbitmq/client/test/TlsUtilsTest.java +++ b/src/test/java/com/rabbitmq/client/test/TlsUtilsTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.security.cert.CertificateParsingException; diff --git a/src/test/java/com/rabbitmq/client/test/TrafficListenerTest.java b/src/test/java/com/rabbitmq/client/test/TrafficListenerTest.java index ebc25349d4..db8d021194 100644 --- a/src/test/java/com/rabbitmq/client/test/TrafficListenerTest.java +++ b/src/test/java/com/rabbitmq/client/test/TrafficListenerTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -21,9 +21,8 @@ import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.TrafficListener; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.List; import java.util.UUID; @@ -32,20 +31,16 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * */ -@RunWith(Parameterized.class) public class TrafficListenerTest { - @Parameterized.Parameter - public Consumer configurator; - @Parameterized.Parameters - public static Object[] data() { + static Object[] trafficListenerIsCalled() { return new Object[] { automaticRecoveryEnabled(), automaticRecoveryDisabled() }; } @@ -57,8 +52,9 @@ static Consumer automaticRecoveryDisabled() { return cf -> cf.setAutomaticRecoveryEnabled(false); } - @Test - public void trafficListenerIsCalled() throws Exception { + @ParameterizedTest + @MethodSource + public void trafficListenerIsCalled(Consumer configurator) throws Exception { ConnectionFactory cf = TestUtils.connectionFactory(); TestTrafficListener testTrafficListener = new TestTrafficListener(); cf.setTrafficListener(testTrafficListener); diff --git a/src/test/java/com/rabbitmq/client/test/TruncatedInputStreamTest.java b/src/test/java/com/rabbitmq/client/test/TruncatedInputStreamTest.java index 3adc9492a0..5d4a9d1273 100644 --- a/src/test/java/com/rabbitmq/client/test/TruncatedInputStreamTest.java +++ b/src/test/java/com/rabbitmq/client/test/TruncatedInputStreamTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,15 +16,15 @@ package com.rabbitmq.client.test; import com.rabbitmq.client.impl.TruncatedInputStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Some basic (retroactive) tests for TruncatedInputStream. @@ -40,12 +40,12 @@ public class TruncatedInputStreamTest { /** what length to truncate it to */ private static final int TRUNCATED_LENGTH = 3; - @Before public void setUp() throws Exception { + @BeforeEach public void setUp() throws Exception { InputStream baseStream = new ByteArrayInputStream(TEST_BYTES); _truncStream = new TruncatedInputStream(baseStream, TRUNCATED_LENGTH); } - @After public void tearDown() throws Exception { + @AfterEach public void tearDown() throws Exception { _truncStream = null; } diff --git a/src/test/java/com/rabbitmq/client/test/ValueOrExceptionTest.java b/src/test/java/com/rabbitmq/client/test/ValueOrExceptionTest.java index 1ae80029be..ac9a38b767 100644 --- a/src/test/java/com/rabbitmq/client/test/ValueOrExceptionTest.java +++ b/src/test/java/com/rabbitmq/client/test/ValueOrExceptionTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,9 +17,9 @@ import com.rabbitmq.utility.SensibleClone; import com.rabbitmq.utility.ValueOrException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class ValueOrExceptionTest { diff --git a/src/test/java/com/rabbitmq/client/test/functional/AbstractRejectTest.java b/src/test/java/com/rabbitmq/client/test/functional/AbstractRejectTest.java index 8c87db34f1..82b8b78035 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/AbstractRejectTest.java +++ b/src/test/java/com/rabbitmq/client/test/functional/AbstractRejectTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,9 +16,9 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Arrays; @@ -29,27 +29,32 @@ import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.test.BrokerTestCase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInfo; abstract class AbstractRejectTest extends BrokerTestCase { protected Channel secondaryChannel; + @BeforeEach @Override - public void setUp() + public void setUp(TestInfo info) throws IOException, TimeoutException { - super.setUp(); + super.setUp(info); secondaryChannel = connection.createChannel(); } + @AfterEach @Override - public void tearDown() + public void tearDown(TestInfo info) throws IOException, TimeoutException { if (secondaryChannel != null) { secondaryChannel.abort(); secondaryChannel = null; } - super.tearDown(); + super.tearDown(info); } protected long checkDelivery(QueueingConsumer.Delivery d, diff --git a/src/test/java/com/rabbitmq/client/test/functional/AlternateExchange.java b/src/test/java/com/rabbitmq/client/test/functional/AlternateExchange.java index 8f2dd6675a..816d9f70f5 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/AlternateExchange.java +++ b/src/test/java/com/rabbitmq/client/test/functional/AlternateExchange.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,7 +16,7 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.HashMap; @@ -24,12 +24,14 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.ReturnListener; import com.rabbitmq.client.test.BrokerTestCase; +import org.junit.jupiter.api.TestInfo; public class AlternateExchange extends BrokerTestCase { @@ -59,8 +61,9 @@ private static boolean[] expected(String key) { return expected; } - @Override public void setUp() throws IOException, TimeoutException { - super.setUp(); + @BeforeEach + @Override public void setUp(TestInfo info) throws IOException, TimeoutException { + super.setUp(info); channel.addReturnListener(new ReturnListener() { public void handleReturn(int replyCode, String replyText, @@ -131,7 +134,7 @@ protected void checkGet(boolean[] expected) throws IOException { for (int i = 0; i < resources.length; i++) { String q = resources[i]; GetResponse r = channel.basicGet(q, true); - assertEquals("check " + q , expected[i], r != null); + assertEquals(expected[i], r != null, "check " + q); } } diff --git a/src/test/java/com/rabbitmq/client/test/functional/BasicConsume.java b/src/test/java/com/rabbitmq/client/test/functional/BasicConsume.java index 06b5fb588f..38adbf71ee 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/BasicConsume.java +++ b/src/test/java/com/rabbitmq/client/test/functional/BasicConsume.java @@ -5,13 +5,13 @@ import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -27,7 +27,7 @@ public class BasicConsume extends BrokerTestCase { channel.basicConsume(q, new CountDownLatchConsumer(channel, latch)); boolean nbOfExpectedMessagesHasBeenConsumed = latch.await(1, TimeUnit.SECONDS); - assertTrue("Not all the messages have been received", nbOfExpectedMessagesHasBeenConsumed); + assertTrue(nbOfExpectedMessagesHasBeenConsumed, "Not all the messages have been received"); } static class CountDownLatchConsumer extends DefaultConsumer { diff --git a/src/test/java/com/rabbitmq/client/test/functional/BasicGet.java b/src/test/java/com/rabbitmq/client/test/functional/BasicGet.java index e64dee9e9a..0956e8cc35 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/BasicGet.java +++ b/src/test/java/com/rabbitmq/client/test/functional/BasicGet.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,16 +15,16 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AlreadyClosedException; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycle.java b/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycle.java index 91a5c54d49..a478748a7d 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycle.java +++ b/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycle.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,16 +16,16 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.GetResponse; @@ -53,7 +53,7 @@ public class BindingLifecycle extends BindingLifecycleBase { channel.queuePurge(binding.q); GetResponse response = channel.basicGet(binding.q, true); - assertNull("The response SHOULD BE null", response); + assertNull(response, "The response SHOULD BE null"); deleteExchangeAndQueue(binding); } @@ -71,24 +71,24 @@ public class BindingLifecycle extends BindingLifecycleBase { GetResponse response = channel.basicGet(binding.q, false); assertFalse(response.getEnvelope().isRedeliver()); - assertNotNull("The response SHOULD NOT BE null", response); + assertNotNull(response, "The response SHOULD NOT BE null"); // If we purge the queue the unacked message should still be there on // recover. channel.queuePurge(binding.q); response = channel.basicGet(binding.q, true); - assertNull("The response SHOULD BE null", response); + assertNull(response, "The response SHOULD BE null"); channel.basicRecover(); response = channel.basicGet(binding.q, false); channel.basicRecover(); assertTrue(response.getEnvelope().isRedeliver()); - assertNotNull("The response SHOULD NOT BE null", response); + assertNotNull(response, "The response SHOULD NOT BE null"); // If we recover then purge the message should go away channel.queuePurge(binding.q); response = channel.basicGet(binding.q, true); - assertNull("The response SHOULD BE null", response); + assertNull(response, "The response SHOULD BE null"); deleteExchangeAndQueue(binding); } diff --git a/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycleBase.java b/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycleBase.java index 51c0e93585..c3b7995c27 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycleBase.java +++ b/src/test/java/com/rabbitmq/client/test/functional/BindingLifecycleBase.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,9 +16,9 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; @@ -120,13 +120,13 @@ protected void restart() throws IOException, TimeoutException { protected void sendRoutable(Binding binding) throws IOException { channel.basicPublish(binding.x, binding.k, null, payload); GetResponse response = channel.basicGet(binding.q, true); - assertNotNull("The response should not be null", response); + assertNotNull(response, "The response should not be null"); } protected void sendUnroutable(Binding binding) throws IOException { channel.basicPublish(binding.x, binding.k, null, payload); GetResponse response = channel.basicGet(binding.q, true); - assertNull("The response SHOULD BE null", response); + assertNull(response, "The response SHOULD BE null"); } protected Binding setupExchangeAndRouteMessage(boolean durable) throws IOException { diff --git a/src/test/java/com/rabbitmq/client/test/functional/CcRoutes.java b/src/test/java/com/rabbitmq/client/test/functional/CcRoutes.java index ebb54164a3..b65d2ad740 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/CcRoutes.java +++ b/src/test/java/com/rabbitmq/client/test/functional/CcRoutes.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,11 +15,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.*; @@ -27,12 +27,14 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.test.BrokerTestCase; +import org.junit.jupiter.api.TestInfo; public class CcRoutes extends BrokerTestCase { @@ -44,8 +46,9 @@ public class CcRoutes extends BrokerTestCase { private List ccList; private List bccList; - @Override public void setUp() throws IOException, TimeoutException { - super.setUp(); + @BeforeEach + @Override public void setUp(TestInfo info) throws IOException, TimeoutException { + super.setUp(info); propsBuilder = new BasicProperties.Builder(); headers = new HashMap<>(); ccList = new ArrayList<>(); diff --git a/src/test/java/com/rabbitmq/client/test/functional/ClusteredTestBase.java b/src/test/java/com/rabbitmq/client/test/functional/ClusteredTestBase.java index 06f53f715a..2580ed0daf 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ClusteredTestBase.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ClusteredTestBase.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/Confirm.java b/src/test/java/com/rabbitmq/client/test/functional/Confirm.java index 0c427bd261..0dbf5950c8 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Confirm.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Confirm.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,8 +16,10 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; @@ -35,6 +37,7 @@ import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.TestInfo; public class Confirm extends BrokerTestCase { @@ -42,9 +45,10 @@ public class Confirm extends BrokerTestCase private static final String TTL_ARG = "x-message-ttl"; + @BeforeEach @Override - public void setUp() throws IOException, TimeoutException { - super.setUp(); + public void setUp(TestInfo info) throws IOException, TimeoutException { + super.setUp(info); channel.confirmSelect(); channel.queueDeclare("confirm-test", true, true, false, null); channel.queueDeclare("confirm-durable-nonexclusive", true, false, diff --git a/src/test/java/com/rabbitmq/client/test/functional/ConnectionOpen.java b/src/test/java/com/rabbitmq/client/test/functional/ConnectionOpen.java index 22fe19e326..646f9e054d 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ConnectionOpen.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ConnectionOpen.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,9 +16,9 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.DataInputStream; import java.io.IOException; @@ -26,7 +26,7 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.ConnectionFactory; @@ -49,13 +49,12 @@ public class ConnectionOpen { while (!command.handleFrame(fh.readFrame())) { } Method m = command.getMethod(); - assertTrue("First command must be Connection.start", - m instanceof AMQP.Connection.Start); + assertTrue(m instanceof AMQP.Connection.Start, "First command must be Connection.start"); AMQP.Connection.Start start = (AMQP.Connection.Start) m; - assertTrue("Version in Connection.start is <= what we sent", - start.getVersionMajor() < AMQP.PROTOCOL.MAJOR || + assertTrue(start.getVersionMajor() < AMQP.PROTOCOL.MAJOR || (start.getVersionMajor() == AMQP.PROTOCOL.MAJOR && - start.getVersionMinor() <= AMQP.PROTOCOL.MINOR)); + start.getVersionMinor() <= AMQP.PROTOCOL.MINOR), + "Version in Connection.start is <= what we sent"); } @Test public void crazyProtocolHeader() throws IOException { diff --git a/src/test/java/com/rabbitmq/client/test/functional/ConnectionRecovery.java b/src/test/java/com/rabbitmq/client/test/functional/ConnectionRecovery.java index f74ca5e3ae..0f9ff4a055 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ConnectionRecovery.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ConnectionRecovery.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -23,7 +23,7 @@ import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.client.test.TestUtils; import com.rabbitmq.tools.Host; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ConsumerCancelNotification.java b/src/test/java/com/rabbitmq/client/test/functional/ConsumerCancelNotification.java index 1c68176d76..7d8631a100 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ConsumerCancelNotification.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ConsumerCancelNotification.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,7 +20,7 @@ import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.ShutdownSignalException; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; @@ -28,8 +28,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class ConsumerCancelNotification extends BrokerTestCase { diff --git a/src/test/java/com/rabbitmq/client/test/functional/ConsumerCount.java b/src/test/java/com/rabbitmq/client/test/functional/ConsumerCount.java index b0ba1c3206..eca4b57c48 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ConsumerCount.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ConsumerCount.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,11 +15,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ConsumerPriorities.java b/src/test/java/com/rabbitmq/client/test/functional/ConsumerPriorities.java index 10bde1f0f1..db0ebc1212 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ConsumerPriorities.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ConsumerPriorities.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,10 +16,10 @@ package com.rabbitmq.client.test.functional; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Arrays; @@ -75,15 +75,15 @@ private void assertFailValidation(Map args) throws IOException { assertContents(highConsumer, COUNT, "high"); channel.basicCancel(high); assertTrue( - "High priority consumer should have been cancelled", - highConsumer.cancelLatch.await(CANCEL_OK_TIMEOUT_MS, TimeUnit.MILLISECONDS) + highConsumer.cancelLatch.await(CANCEL_OK_TIMEOUT_MS, TimeUnit.MILLISECONDS), + "High priority consumer should have been cancelled" ); publish(queue, COUNT, "med"); assertContents(medConsumer, COUNT, "med"); channel.basicCancel(med); assertTrue( - "Medium priority consumer should have been cancelled", - medConsumer.cancelLatch.await(CANCEL_OK_TIMEOUT_MS, TimeUnit.MILLISECONDS) + medConsumer.cancelLatch.await(CANCEL_OK_TIMEOUT_MS, TimeUnit.MILLISECONDS), + "Medium priority consumer should have been cancelled" ); publish(queue, COUNT, "low"); assertContents(lowConsumer, COUNT, "low"); diff --git a/src/test/java/com/rabbitmq/client/test/functional/DeadLetterExchange.java b/src/test/java/com/rabbitmq/client/test/functional/DeadLetterExchange.java index 36c09add6a..5ac9e20895 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/DeadLetterExchange.java +++ b/src/test/java/com/rabbitmq/client/test/functional/DeadLetterExchange.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,15 +19,20 @@ import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.*; import java.util.concurrent.*; -import static org.junit.Assert.*; +import static com.rabbitmq.client.test.TestUtils.safeDelete; +import static com.rabbitmq.client.test.TestUtils.waitAtMost; +import static java.time.Duration.ofSeconds; +import static org.junit.jupiter.api.Assertions.*; public class DeadLetterExchange extends BrokerTestCase { + public static final String DLX = "dead.letter.exchange"; private static final String DLX_ARG = "x-dead-letter-exchange"; private static final String DLX_RK_ARG = "x-dead-letter-routing-key"; @@ -341,21 +346,28 @@ protected void releaseResources() throws IOException { // messages in pure-expiry cycles. So we just need to test that // non-pure-expiry cycles do not drop messages. - declareQueue("queue1", "", "queue2", null, 1); - declareQueue("queue2", "", "queue1", null, 0); - - channel.basicPublish("", "queue1", MessageProperties.BASIC, "".getBytes()); - final CountDownLatch latch = new CountDownLatch(10); - channel.basicConsume("queue2", false, - new DefaultConsumer(channel) { - @Override - public void handleDelivery(String consumerTag, Envelope envelope, - AMQP.BasicProperties properties, byte[] body) throws IOException { - channel.basicReject(envelope.getDeliveryTag(), false); - latch.countDown(); - } - }); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + String queue1 = generateQueueName(); + String queue2 = generateQueueName(); + try { + declareQueue(queue1, "", queue2, null, 1); + declareQueue(queue2, "", queue1, null, 0); + + channel.basicPublish("", queue1, MessageProperties.BASIC, "".getBytes()); + final CountDownLatch latch = new CountDownLatch(10); + channel.basicConsume(queue2, false, + new DefaultConsumer(channel) { + @Override + public void handleDelivery(String consumerTag, Envelope envelope, + AMQP.BasicProperties properties, byte[] body) throws IOException { + channel.basicReject(envelope.getDeliveryTag(), false); + latch.countDown(); + } + }); + assertTrue(latch.await(10, TimeUnit.SECONDS)); + } finally { + safeDelete(connection, queue1); + safeDelete(connection, queue2); + } } @SuppressWarnings("unchecked") @@ -403,11 +415,16 @@ public void handleDelivery(String consumerTag, Envelope envelope, channel.queueBind(DLQ, DLX, "test"); publishN(1); - sleep(200); - - GetResponse getResponse = channel.basicGet(DLQ, true); - assertNotNull("Message not dead-lettered", - getResponse); + AtomicReference responseRefeference = new AtomicReference<>(); + waitAtMost( + ofSeconds(1), + () -> { + GetResponse response = channel.basicGet(DLQ, true); + responseRefeference.set(response); + return responseRefeference.get() != null; + }); + GetResponse getResponse = responseRefeference.get(); + assertNotNull(getResponse, "Message not dead-lettered"); assertEquals("test message", new String(getResponse.getBody())); BasicProperties props = getResponse.getProps(); Map headers = props.getHeaders(); @@ -432,10 +449,16 @@ public void handleDelivery(String consumerTag, Envelope envelope, .headers(headers) .build(), "test message".getBytes()); - sleep(100); - - getResponse = channel.basicGet(DLQ, true); - assertNotNull("Message not dead-lettered", getResponse); + responseRefeference.set(null); + waitAtMost( + ofSeconds(1), + () -> { + GetResponse response = channel.basicGet(DLQ, true); + responseRefeference.set(response); + return responseRefeference.get() != null; + }); + getResponse = responseRefeference.get(); + assertNotNull(getResponse, "Message not dead-lettered"); assertEquals("test message", new String(getResponse.getBody())); headers = getResponse.getProps().getHeaders(); assertNotNull(headers); @@ -453,10 +476,18 @@ public void handleDelivery(String consumerTag, Envelope envelope, new AMQP.BasicProperties.Builder() .headers(headers) .build(), "test message".getBytes()); - sleep(100); - getResponse = channel.basicGet(DLQ, true); - assertNotNull("Message not dead-lettered", getResponse); + responseRefeference.set(null); + waitAtMost( + ofSeconds(1), + () -> { + GetResponse response = channel.basicGet(DLQ, true); + responseRefeference.set(response); + return responseRefeference.get() != null; + }); + getResponse = responseRefeference.get(); + + assertNotNull(getResponse, "Message not dead-lettered"); assertEquals("test message", new String(getResponse.getBody())); headers = getResponse.getProps().getHeaders(); assertNotNull(headers); @@ -555,14 +586,14 @@ private void checkPromptArrival(AccumulatingMessageConsumer c, long epsilon = TTL / 5; for (int i = 0; i < count; i++) { byte[] body = c.nextDelivery(TTL + TTL + latency + epsilon); - assertNotNull("message #" + i + " did not expire", body); + assertNotNull(body, "message #" + i + " did not expire"); long now = System.currentTimeMillis(); long publishTime = Long.valueOf(new String(body)); long targetTime = publishTime + TTL + latency; - assertTrue("expiry outside bounds (+/- " + epsilon + "): " + - (now - targetTime), - (now >= targetTime - epsilon) && - (now <= targetTime + epsilon)); + assertTrue((now >= targetTime - epsilon) && + (now <= targetTime + epsilon), + "expiry outside bounds (+/- " + epsilon + "): " + + (now - targetTime)); } } @@ -634,13 +665,12 @@ private static void consumeN(Channel channel, String queue, int n, WithResponse for(int x = 0; x < n; x++) { GetResponse getResponse = channel.basicGet(queue, true); - assertNotNull("Messages not dead-lettered (" + (n-x) + " left)", - getResponse); + assertNotNull(getResponse, "Messages not dead-lettered (" + (n-x) + " left)"); assertEquals("test message", new String(getResponse.getBody())); withResponse.process(getResponse); } GetResponse getResponse = channel.basicGet(queue, true); - assertNull("expected empty queue", getResponse); + assertNull(getResponse, "expected empty queue"); } @SuppressWarnings("unchecked") diff --git a/src/test/java/com/rabbitmq/client/test/functional/DefaultExchange.java b/src/test/java/com/rabbitmq/client/test/functional/DefaultExchange.java index 7d0e9f7899..72c2793f9b 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/DefaultExchange.java +++ b/src/test/java/com/rabbitmq/client/test/functional/DefaultExchange.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,11 +15,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/DirectReplyTo.java b/src/test/java/com/rabbitmq/client/test/functional/DirectReplyTo.java index 2cef783ba1..84911f447c 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/DirectReplyTo.java +++ b/src/test/java/com/rabbitmq/client/test/functional/DirectReplyTo.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,11 +15,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.BlockingQueue; @@ -27,7 +27,7 @@ import java.util.concurrent.TimeUnit; import com.rabbitmq.client.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.BrokerTestCase; @@ -92,7 +92,7 @@ private void declare(Connection connection, String q, boolean expectedExists) th } } - @Test public void consumeSuccess() throws IOException, InterruptedException { + @Test public void consumeSuccess() throws IOException { DefaultConsumer c = new DefaultConsumer(channel); String ctag = channel.basicConsume(QUEUE, true, c); channel.basicCancel(ctag); diff --git a/src/test/java/com/rabbitmq/client/test/functional/DoubleDeletion.java b/src/test/java/com/rabbitmq/client/test/functional/DoubleDeletion.java index 14f6dee293..c28bab794c 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/DoubleDeletion.java +++ b/src/test/java/com/rabbitmq/client/test/functional/DoubleDeletion.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -18,7 +18,7 @@ import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/DurableOnTransient.java b/src/test/java/com/rabbitmq/client/test/functional/DurableOnTransient.java index cfc00d7b0a..3732ff55ac 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/DurableOnTransient.java +++ b/src/test/java/com/rabbitmq/client/test/functional/DurableOnTransient.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,11 +16,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.MessageProperties; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExceptionHandling.java b/src/test/java/com/rabbitmq/client/test/functional/ExceptionHandling.java index 611a8eea82..700a6dda52 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExceptionHandling.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExceptionHandling.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,8 +15,8 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.CountDownLatch; @@ -24,7 +24,7 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExceptionMessages.java b/src/test/java/com/rabbitmq/client/test/functional/ExceptionMessages.java index 68f4da2204..672db4dfa8 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExceptionMessages.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExceptionMessages.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,13 +15,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.UUID; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AlreadyClosedException; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeclare.java b/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeclare.java index 7c1e6f2e76..b6976ee873 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeclare.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeclare.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,7 +16,7 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.HashMap; @@ -24,7 +24,7 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; @@ -101,7 +101,7 @@ public void releaseResources() throws IOException { } private void doTestExchangeDeclaredWithEnumerationEquivalent(Channel channel) throws IOException, InterruptedException { - assertEquals("There are 4 standard exchange types", 4, BuiltinExchangeType.values().length); + assertEquals(4, BuiltinExchangeType.values().length, "There are 4 standard exchange types"); for (BuiltinExchangeType exchangeType : BuiltinExchangeType.values()) { channel.exchangeDeclare(NAME, exchangeType); verifyEquivalent(NAME, exchangeType.getType(), false, false, null); diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeleteIfUnused.java b/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeleteIfUnused.java index bbaf6b323c..299d95567f 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeleteIfUnused.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeleteIfUnused.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,12 +16,12 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeletePredeclared.java b/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeletePredeclared.java index 28d4d667f6..4229c888ed 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeletePredeclared.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExchangeDeletePredeclared.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExchangeEquivalenceBase.java b/src/test/java/com/rabbitmq/client/test/functional/ExchangeEquivalenceBase.java index 830a2b89e5..cfeed037d4 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExchangeEquivalenceBase.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExchangeEquivalenceBase.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Map; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindings.java b/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindings.java index cc50182001..3416b334d6 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindings.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindings.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,12 +16,12 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.QueueingConsumer.Delivery; diff --git a/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindingsAutoDelete.java b/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindingsAutoDelete.java index ff8cb0a846..a6f01e20c4 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindingsAutoDelete.java +++ b/src/test/java/com/rabbitmq/client/test/functional/ExchangeExchangeBindingsAutoDelete.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,11 +16,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/FrameMax.java b/src/test/java/com/rabbitmq/client/test/functional/FrameMax.java index bfe1bcd826..bafceed32d 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/FrameMax.java +++ b/src/test/java/com/rabbitmq/client/test/functional/FrameMax.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,9 +16,9 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; @@ -32,7 +32,7 @@ import com.rabbitmq.client.impl.AMQBasicProperties; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Address; diff --git a/src/test/java/com/rabbitmq/client/test/functional/FunctionalTests.java b/src/test/java/com/rabbitmq/client/test/functional/FunctionalTestSuite.java similarity index 84% rename from src/test/java/com/rabbitmq/client/test/functional/FunctionalTests.java rename to src/test/java/com/rabbitmq/client/test/functional/FunctionalTestSuite.java index db87a38695..bbf06691e1 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/FunctionalTests.java +++ b/src/test/java/com/rabbitmq/client/test/functional/FunctionalTestSuite.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,14 +17,12 @@ package com.rabbitmq.client.test.functional; import com.rabbitmq.client.impl.WorkPoolTests; -import com.rabbitmq.client.test.AbstractRMQTestSuite; import com.rabbitmq.client.test.Bug20004Test; -import com.rabbitmq.client.test.RequiredPropertiesSuite; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; -@RunWith(RequiredPropertiesSuite.class) -@Suite.SuiteClasses({ +@Suite +@SelectClasses({ ConnectionOpen.class, Heartbeat.class, Tables.class, @@ -81,11 +79,6 @@ TopologyRecoveryFiltering.class, TopologyRecoveryRetry.class }) -public class FunctionalTests { - - // initialize system properties - static{ - new AbstractRMQTestSuite(){}; - } +public class FunctionalTestSuite { } diff --git a/src/test/java/com/rabbitmq/client/test/functional/HeadersExchangeValidation.java b/src/test/java/com/rabbitmq/client/test/functional/HeadersExchangeValidation.java index b2eeee7719..49b0779c8c 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/HeadersExchangeValidation.java +++ b/src/test/java/com/rabbitmq/client/test/functional/HeadersExchangeValidation.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,12 +15,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; +import com.rabbitmq.client.test.TestUtils; import java.io.IOException; import java.util.HashMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; @@ -47,6 +48,14 @@ public class HeadersExchangeValidation extends BrokerTestCase { arguments.put("x-match", "any"); succeedBind(queue, arguments); + + if (TestUtils.isVersion310orLater(connection)) { + arguments.put("x-match", "all-with-x"); + succeedBind(queue, arguments); + + arguments.put("x-match", "any-with-x"); + succeedBind(queue, arguments); + } } private void failBind(String queue, HashMap arguments) { diff --git a/src/test/java/com/rabbitmq/client/test/functional/Heartbeat.java b/src/test/java/com/rabbitmq/client/test/functional/Heartbeat.java index 62611f2a35..002c60b487 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Heartbeat.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Heartbeat.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,11 +19,11 @@ import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.impl.recovery.AutorecoveringConnection; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class Heartbeat extends BrokerTestCase { diff --git a/src/test/java/com/rabbitmq/client/test/functional/InternalExchange.java b/src/test/java/com/rabbitmq/client/test/functional/InternalExchange.java index 43a571afc8..12bfc7c76d 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/InternalExchange.java +++ b/src/test/java/com/rabbitmq/client/test/functional/InternalExchange.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,12 +16,12 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.GetResponse; diff --git a/src/test/java/com/rabbitmq/client/test/functional/InvalidAcks.java b/src/test/java/com/rabbitmq/client/test/functional/InvalidAcks.java index 217c55e1c9..08dc083f6f 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/InvalidAcks.java +++ b/src/test/java/com/rabbitmq/client/test/functional/InvalidAcks.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksBase.java b/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksBase.java index 1c249007bd..f24e848c63 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksBase.java +++ b/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksBase.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,7 +20,7 @@ import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * See bug 21846: diff --git a/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksTx.java b/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksTx.java index 81fc7e61f7..2df62e23ed 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksTx.java +++ b/src/test/java/com/rabbitmq/client/test/functional/InvalidAcksTx.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/MessageCount.java b/src/test/java/com/rabbitmq/client/test/functional/MessageCount.java index 3cb81344af..8ccef02846 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/MessageCount.java +++ b/src/test/java/com/rabbitmq/client/test/functional/MessageCount.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,11 +15,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/Metrics.java b/src/test/java/com/rabbitmq/client/test/functional/Metrics.java index 89281b21df..0c745ebdff 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Metrics.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Metrics.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -31,9 +31,7 @@ import com.rabbitmq.client.test.TestUtils; import com.rabbitmq.tools.Host; import java.util.UUID; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.lang.reflect.Field; @@ -49,6 +47,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static com.rabbitmq.client.test.TestUtils.waitAtMost; import static org.assertj.core.api.Assertions.assertThat; @@ -56,17 +56,12 @@ /** * */ -@RunWith(Parameterized.class) public class Metrics extends BrokerTestCase { - @Parameterized.Parameters public static Object[] data() { return new Object[] { createConnectionFactory(), createAutoRecoveryConnectionFactory() }; } - @Parameterized.Parameter - public ConnectionFactory connectionFactory; - static final String QUEUE = "metrics.queue"; @Override @@ -79,7 +74,9 @@ protected void releaseResources() throws IOException { channel.queueDelete(QUEUE); } - @Test public void metrics() throws IOException, TimeoutException { + @ParameterizedTest + @MethodSource("data") + public void metrics(ConnectionFactory connectionFactory) throws IOException, TimeoutException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); Connection connection1 = null; @@ -138,7 +135,9 @@ protected void releaseResources() throws IOException { } } - @Test public void metricsPublisherUnrouted() throws IOException, TimeoutException { + @ParameterizedTest + @MethodSource("data") + public void metricsPublisherUnrouted(ConnectionFactory connectionFactory) throws IOException, TimeoutException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); Connection connection = null; @@ -162,7 +161,9 @@ protected void releaseResources() throws IOException { } } - @Test public void metricsPublisherAck() throws IOException, TimeoutException, InterruptedException { + @ParameterizedTest + @MethodSource("data") + public void metricsPublisherAck(ConnectionFactory connectionFactory) throws IOException, TimeoutException, InterruptedException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); Connection connection = null; @@ -176,13 +177,15 @@ protected void releaseResources() throws IOException { sendMessage(channel); channel.waitForConfirms(30 * 60 * 1000); // then - assertThat(metrics.getPublishAcknowledgedMessages().getCount()).isEqualTo(1L); + waitAtMost(Duration.ofSeconds(5), () -> metrics.getPublishAcknowledgedMessages().getCount() == 1); } finally { safeClose(connection); } } - @Test public void metricsAck() throws IOException, TimeoutException { + @ParameterizedTest + @MethodSource("data") + public void metricsAck(ConnectionFactory connectionFactory) throws IOException, TimeoutException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); @@ -248,7 +251,9 @@ protected void releaseResources() throws IOException { } } - @Test public void metricsReject() throws IOException, TimeoutException { + @ParameterizedTest + @MethodSource("data") + public void metricsReject(ConnectionFactory connectionFactory) throws IOException, TimeoutException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); @@ -275,7 +280,9 @@ protected void releaseResources() throws IOException { } } - @Test public void multiThreadedMetricsStandardConnection() throws InterruptedException, TimeoutException, IOException { + @ParameterizedTest + @MethodSource("data") + public void multiThreadedMetricsStandardConnection(ConnectionFactory connectionFactory) throws InterruptedException, TimeoutException, IOException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); int nbConnections = 3; @@ -385,7 +392,9 @@ protected void releaseResources() throws IOException { } } - @Test public void errorInChannel() throws IOException, TimeoutException { + @ParameterizedTest + @MethodSource("data") + public void errorInChannel(ConnectionFactory connectionFactory) throws IOException, TimeoutException { StandardMetricsCollector metrics = new StandardMetricsCollector(); connectionFactory.setMetricsCollector(metrics); diff --git a/src/test/java/com/rabbitmq/client/test/functional/Nack.java b/src/test/java/com/rabbitmq/client/test/functional/Nack.java index ce9b70ddd0..6bd47e6067 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Nack.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Nack.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,8 +16,8 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.rabbitmq.client.Channel; import com.rabbitmq.client.test.TestUtils; @@ -27,17 +27,14 @@ import java.util.Set; import java.util.UUID; -import org.junit.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.QueueingConsumer; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class Nack extends AbstractRejectTest { - @Parameterized.Parameters public static Object[] queueCreators() { return new Object[] { (CallableFunction) channel -> { @@ -52,9 +49,9 @@ public static Object[] queueCreators() { }}; } - @Parameterized.Parameter public TestUtils.CallableFunction queueCreator; - - @Test public void singleNack() throws Exception { + @ParameterizedTest + @MethodSource("queueCreators") + public void singleNack(TestUtils.CallableFunction queueCreator) throws Exception { String q = queueCreator.apply(channel); byte[] m1 = "1".getBytes(); @@ -89,7 +86,9 @@ public static Object[] queueCreators() { expectError(AMQP.PRECONDITION_FAILED); } - @Test public void multiNack() throws Exception { + @ParameterizedTest + @MethodSource("queueCreators") + public void multiNack(TestUtils.CallableFunction queueCreator) throws Exception { String q = queueCreator.apply(channel); byte[] m1 = "1".getBytes(); @@ -134,7 +133,9 @@ public static Object[] queueCreators() { expectError(AMQP.PRECONDITION_FAILED); } - @Test public void nackAll() throws Exception { + @ParameterizedTest + @MethodSource("queueCreators") + public void nackAll(TestUtils.CallableFunction queueCreator) throws Exception { String q = queueCreator.apply(channel); byte[] m1 = "1".getBytes(); @@ -173,7 +174,7 @@ private long checkDeliveries(QueueingConsumer c, byte[]... messages) for(int x = 0; x < messages.length; x++) { QueueingConsumer.Delivery delivery = c.nextDelivery(); String m = new String(delivery.getBody()); - assertTrue("Unexpected message", msgSet.remove(m)); + assertTrue(msgSet.remove(m), "Unexpected message"); checkDelivery(delivery, m.getBytes(), true); lastTag = delivery.getEnvelope().getDeliveryTag(); } diff --git a/src/test/java/com/rabbitmq/client/test/functional/NoRequeueOnCancel.java b/src/test/java/com/rabbitmq/client/test/functional/NoRequeueOnCancel.java index 41d68d94d5..f93f8f591b 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/NoRequeueOnCancel.java +++ b/src/test/java/com/rabbitmq/client/test/functional/NoRequeueOnCancel.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,16 +16,16 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.rabbitmq.client.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/Nowait.java b/src/test/java/com/rabbitmq/client/test/functional/Nowait.java index 5f713fff61..b795f02482 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Nowait.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Nowait.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/PerConsumerPrefetch.java b/src/test/java/com/rabbitmq/client/test/functional/PerConsumerPrefetch.java index 4a36a22052..51149c613f 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/PerConsumerPrefetch.java +++ b/src/test/java/com/rabbitmq/client/test/functional/PerConsumerPrefetch.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -21,7 +21,7 @@ import java.util.Arrays; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.QueueingConsumer; diff --git a/src/test/java/com/rabbitmq/client/test/functional/PerMessageTTL.java b/src/test/java/com/rabbitmq/client/test/functional/PerMessageTTL.java index ab09bdbfdd..2b6bb3ed99 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/PerMessageTTL.java +++ b/src/test/java/com/rabbitmq/client/test/functional/PerMessageTTL.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,12 +16,12 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.MessageProperties; @@ -58,8 +58,8 @@ protected AMQP.Queue.DeclareOk declareQueue(String name, Object ttlValue) throws QueueingConsumer c = new QueueingConsumer(channel); channel.basicConsume(TTL_QUEUE_NAME, c); - assertNotNull("Message unexpectedly expired", c.nextDelivery(100)); - assertNull("Message should have been expired!!", c.nextDelivery(100)); + assertNotNull(c.nextDelivery(100), "Message unexpectedly expired"); + assertNull(c.nextDelivery(100), "Message should have been expired!!"); } @Test public void restartingExpiry() throws Exception { @@ -71,11 +71,10 @@ protected AMQP.Queue.DeclareOk declareQueue(String name, Object ttlValue) throws .builder() .expiration(expiryDelay) .build(), new byte[]{}); - long expiryStartTime = System.currentTimeMillis(); restart(); Thread.sleep(Integer.parseInt(expiryDelay)); try { - assertNull("Message should have expired after broker restart", get()); + assertNull(get(), "Message should have expired after broker restart"); } finally { deleteQueue(TTL_QUEUE_NAME); } diff --git a/src/test/java/com/rabbitmq/client/test/functional/PerQueueTTL.java b/src/test/java/com/rabbitmq/client/test/functional/PerQueueTTL.java index 506ea50c8f..177a67cd58 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/PerQueueTTL.java +++ b/src/test/java/com/rabbitmq/client/test/functional/PerQueueTTL.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,13 +16,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Collections; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.MessageProperties; diff --git a/src/test/java/com/rabbitmq/client/test/functional/PerQueueVsPerMessageTTL.java b/src/test/java/com/rabbitmq/client/test/functional/PerQueueVsPerMessageTTL.java index 58475877be..e835b42c0f 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/PerQueueVsPerMessageTTL.java +++ b/src/test/java/com/rabbitmq/client/test/functional/PerQueueVsPerMessageTTL.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,13 +15,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.util.Collections; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; @@ -35,7 +35,7 @@ public class PerQueueVsPerMessageTTL extends PerMessageTTL { Thread.sleep(100); - assertNull("per-queue ttl should have removed message after 10ms!", get()); + assertNull(get(), "per-queue ttl should have removed message after 10ms"); } @Override diff --git a/src/test/java/com/rabbitmq/client/test/functional/Policies.java b/src/test/java/com/rabbitmq/client/test/functional/Policies.java index f4d1dd4988..602e2b57c4 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Policies.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Policies.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,9 +15,9 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.HashMap; @@ -25,12 +25,11 @@ import java.util.Map; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.Channel; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.test.BrokerTestCase; -import com.rabbitmq.client.test.server.HATests; import com.rabbitmq.tools.Host; public class Policies extends BrokerTestCase { @@ -184,7 +183,7 @@ private void setPolicy(String name, String pattern, String definition) throws IO // We need to override the HA policy that we use in HATests, so // priority 1. But we still want a valid test of HA, so add the // ha-mode definition. - if (HATests.HA_TESTS_RUNNING) { + if (ha()) { definition += ",\"ha-mode\":\"all\""; } Host.rabbitmqctl("set_policy --priority 1 " + name + " " + pattern + diff --git a/src/test/java/com/rabbitmq/client/test/functional/QosTests.java b/src/test/java/com/rabbitmq/client/test/functional/QosTests.java index 276a363f4e..b14d5526c3 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/QosTests.java +++ b/src/test/java/com/rabbitmq/client/test/functional/QosTests.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,10 +16,10 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.ArrayList; @@ -31,7 +31,7 @@ import java.util.Map; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/functional/QueueExclusivity.java b/src/test/java/com/rabbitmq/client/test/functional/QueueExclusivity.java index 6148ebab27..83df293a10 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/QueueExclusivity.java +++ b/src/test/java/com/rabbitmq/client/test/functional/QueueExclusivity.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,13 +16,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/functional/QueueLease.java b/src/test/java/com/rabbitmq/client/test/functional/QueueLease.java index 284f6bd67d..46a31f8b3e 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/QueueLease.java +++ b/src/test/java/com/rabbitmq/client/test/functional/QueueLease.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,13 +16,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Consumer; diff --git a/src/test/java/com/rabbitmq/client/test/functional/QueueLifecycle.java b/src/test/java/com/rabbitmq/client/test/functional/QueueLifecycle.java index 8ee54671dc..ceedb520ad 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/QueueLifecycle.java +++ b/src/test/java/com/rabbitmq/client/test/functional/QueueLifecycle.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,14 +20,14 @@ import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test queue auto-delete and exclusive semantics. diff --git a/src/test/java/com/rabbitmq/client/test/functional/QueueSizeLimit.java b/src/test/java/com/rabbitmq/client/test/functional/QueueSizeLimit.java index 8d34862543..c0c9350173 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/QueueSizeLimit.java +++ b/src/test/java/com/rabbitmq/client/test/functional/QueueSizeLimit.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,9 +16,9 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.util.ArrayList; @@ -26,7 +26,7 @@ import java.util.List; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/Recover.java b/src/test/java/com/rabbitmq/client/test/functional/Recover.java index 61d48973ce..a83c75c9ca 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Recover.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Recover.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,10 +16,10 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Arrays; @@ -28,7 +28,7 @@ import java.util.concurrent.atomic.AtomicReference; import com.rabbitmq.client.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.BrokerTestCase; @@ -56,14 +56,12 @@ void verifyRedeliverOnRecover(RecoverCallback call) channel.basicConsume(queue, false, consumer); // require acks. channel.basicPublish("", queue, new AMQP.BasicProperties.Builder().build(), body); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); - assertTrue("consumed message body not as sent", - Arrays.equals(body, delivery.getBody())); + assertTrue(Arrays.equals(body, delivery.getBody()), "consumed message body not as sent"); // Don't ack it, and get it redelivered to the same consumer call.recover(channel); QueueingConsumer.Delivery secondDelivery = consumer.nextDelivery(5000); - assertNotNull("timed out waiting for redelivered message", secondDelivery); - assertTrue("consumed (redelivered) message body not as sent", - Arrays.equals(body, delivery.getBody())); + assertNotNull(secondDelivery, "timed out waiting for redelivered message"); + assertTrue(Arrays.equals(body, delivery.getBody()), "consumed (redelivered) message body not as sent"); } void verifyNoRedeliveryWithAutoAck(RecoverCallback call) @@ -80,10 +78,9 @@ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProp channel.basicConsume(queue, true, consumer); // auto ack. channel.basicPublish("", queue, new AMQP.BasicProperties.Builder().build(), body); assertTrue(latch.await(5, TimeUnit.SECONDS)); - assertTrue("consumed message body not as sent", - Arrays.equals(body, bodyReference.get())); + assertTrue(Arrays.equals(body, bodyReference.get()), "consumed message body not as sent"); call.recover(channel); - assertNull("should be no message available", channel.basicGet(queue, true)); + assertNull(channel.basicGet(queue, true), "should be no message available"); } final RecoverCallback recoverSync = new RecoverCallback() { diff --git a/src/test/java/com/rabbitmq/client/test/functional/Reject.java b/src/test/java/com/rabbitmq/client/test/functional/Reject.java index c2c5dd76bd..b8abaf0779 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Reject.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Reject.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,7 +16,7 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import com.rabbitmq.client.Channel; import com.rabbitmq.client.test.TestUtils; @@ -24,19 +24,16 @@ import java.util.Collections; import java.util.UUID; -import org.junit.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.QueueingConsumer; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class Reject extends AbstractRejectTest { - @Parameterized.Parameters - public static Object[] queueCreators() { + public static Object[] reject() { return new Object[] { (CallableFunction) channel -> { String q = UUID.randomUUID().toString(); @@ -50,9 +47,9 @@ public static Object[] queueCreators() { }}; } - @Parameterized.Parameter public TestUtils.CallableFunction queueCreator; - - @Test public void reject() + @ParameterizedTest + @MethodSource + public void reject(TestUtils.CallableFunction queueCreator) throws Exception { String q = queueCreator.apply(channel); diff --git a/src/test/java/com/rabbitmq/client/test/functional/RequeueOnChannelClose.java b/src/test/java/com/rabbitmq/client/test/functional/RequeueOnChannelClose.java index 8e6c0c6f9e..250b74acf0 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/RequeueOnChannelClose.java +++ b/src/test/java/com/rabbitmq/client/test/functional/RequeueOnChannelClose.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/RequeueOnClose.java b/src/test/java/com/rabbitmq/client/test/functional/RequeueOnClose.java index e86ed31bdf..7fee64f715 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/RequeueOnClose.java +++ b/src/test/java/com/rabbitmq/client/test/functional/RequeueOnClose.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,8 +15,8 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.BrokerTestCase; @@ -84,9 +84,9 @@ private void publishAndGet(int count, boolean doAck) close(); open(); if (doAck) { - assertNull("Expected missing second basicGet (repeat="+repeat+")", getMessage()); + assertNull(getMessage(), "Expected missing second basicGet (repeat="+repeat+")"); } else { - assertNotNull("Expected present second basicGet (repeat="+repeat+")", getMessage()); + assertNotNull(getMessage(), "Expected present second basicGet (repeat="+repeat+")"); } close(); } @@ -146,10 +146,10 @@ private void publishLotsAndGet() close(); open(); for (int i = 0; i < MESSAGE_COUNT; i++) { - assertNotNull("only got " + i + " out of " + MESSAGE_COUNT + - " messages", channel.basicGet(Q, true)); + assertNotNull(channel.basicGet(Q, true), "only got " + i + " out of " + MESSAGE_COUNT + + " messages"); } - assertNull("got more messages than " + MESSAGE_COUNT + " expected", channel.basicGet(Q, true)); + assertNull(channel.basicGet(Q, true), "got more messages than " + MESSAGE_COUNT + " expected"); channel.queueDelete(Q); close(); closeConnection(); @@ -232,14 +232,13 @@ private void publishLotsAndConsumeSome(boolean ack, boolean cancelBeforeFinish) open(); int requeuedMsgCount = (ack) ? MESSAGE_COUNT - MESSAGES_TO_CONSUME : MESSAGE_COUNT; for (int i = 0; i < requeuedMsgCount; i++) { - assertNotNull("only got " + i + " out of " + requeuedMsgCount + " messages", - channel.basicGet(Q, true)); + assertNotNull(channel.basicGet(Q, true), "only got " + i + " out of " + requeuedMsgCount + " messages"); } int countMoreMsgs = 0; while (null != channel.basicGet(Q, true)) { countMoreMsgs++; } - assertTrue("got " + countMoreMsgs + " more messages than " + requeuedMsgCount + " expected", 0==countMoreMsgs); + assertTrue(0==countMoreMsgs, "got " + countMoreMsgs + " more messages than " + requeuedMsgCount + " expected"); channel.queueDelete(Q); close(); closeConnection(); diff --git a/src/test/java/com/rabbitmq/client/test/functional/RequeueOnConnectionClose.java b/src/test/java/com/rabbitmq/client/test/functional/RequeueOnConnectionClose.java index c212512a95..126c1bd71a 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/RequeueOnConnectionClose.java +++ b/src/test/java/com/rabbitmq/client/test/functional/RequeueOnConnectionClose.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 diff --git a/src/test/java/com/rabbitmq/client/test/functional/Routing.java b/src/test/java/com/rabbitmq/client/test/functional/Routing.java index 050eb379b0..9f681d75e6 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Routing.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Routing.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,11 +16,13 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; +import com.rabbitmq.client.test.TestUtils.BrokerVersion; +import com.rabbitmq.client.test.TestUtils.BrokerVersionAtLeast; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -28,7 +30,7 @@ import java.util.Map; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AlreadyClosedException; @@ -170,6 +172,7 @@ private void checkGet(String queue, boolean messageExpected) spec.put("h1", "12345"); spec.put("h2", "bar"); spec.put("h3", null); + spec.put("x-key-1", "bindings starting with x- get filtered out"); spec.put("x-match", "all"); channel.queueBind(Q1, "amq.match", "", spec); spec.put("x-match", "any"); @@ -226,6 +229,10 @@ private void checkGet(String queue, boolean messageExpected) map.put("h2", "quux"); channel.basicPublish("amq.match", "", props.build(), "8".getBytes()); + map.clear(); + map.put("x-key-1", "bindings starting with x- get filtered out"); + channel.basicPublish("amq.match", "", props.build(), "9".getBytes()); + checkGet(Q1, true); // 4 checkGet(Q1, false); @@ -240,6 +247,48 @@ private void checkGet(String queue, boolean messageExpected) checkGet(Q2, false); } + @Test + @BrokerVersionAtLeast(BrokerVersion.RABBITMQ_3_10) + public void headersWithXRouting() throws Exception { + Map spec = new HashMap(); + spec.put("x-key-1", "value-1"); + spec.put("x-key-2", "value-2"); + spec.put("x-match", "all-with-x"); + channel.queueBind(Q1, "amq.match", "", spec); + spec.put("x-match", "any-with-x"); + channel.queueBind(Q2, "amq.match", "", spec); + + AMQP.BasicProperties.Builder props = new AMQP.BasicProperties.Builder(); + channel.basicPublish("amq.match", "", props.build(), "0".getBytes()); + + Map map = new HashMap(); + props.headers(map); + + map.clear(); + map.put("x-key-1", "value-1"); + channel.basicPublish("amq.match", "", props.build(), "1".getBytes()); + + map.clear(); + map.put("x-key-1", "value-1"); + map.put("x-key-2", "value-2"); + channel.basicPublish("amq.match", "", props.build(), "2".getBytes()); + + map.clear(); + map.put("x-key-1", "value-1"); + map.put("x-key-2", "value-2"); + map.put("x-key-3", "value-3"); + channel.basicPublish("amq.match", "", props.build(), "3".getBytes()); + + checkGet(Q1, true); // 2 + checkGet(Q1, true); // 3 + checkGet(Q1, false); + + checkGet(Q2, true); // 1 + checkGet(Q2, true); // 2 + checkGet(Q2, true); // 3 + checkGet(Q2, false); + } + @Test public void basicReturn() throws IOException { channel.addReturnListener(makeReturnListener()); returnCell = new BlockingCell(); diff --git a/src/test/java/com/rabbitmq/client/test/functional/SaslMechanisms.java b/src/test/java/com/rabbitmq/client/test/functional/SaslMechanisms.java index 631d21a2a5..c40718f732 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/SaslMechanisms.java +++ b/src/test/java/com/rabbitmq/client/test/functional/SaslMechanisms.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Arrays; @@ -23,7 +23,7 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AuthenticationFailureException; import com.rabbitmq.client.Connection; diff --git a/src/test/java/com/rabbitmq/client/test/functional/TTLHandling.java b/src/test/java/com/rabbitmq/client/test/functional/TTLHandling.java index 4a2b23ae5c..8d50b7e059 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/TTLHandling.java +++ b/src/test/java/com/rabbitmq/client/test/functional/TTLHandling.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,14 +15,15 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; +import com.rabbitmq.client.ShutdownSignalException; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.GetResponse; @@ -67,6 +68,8 @@ protected void releaseResources() throws IOException { fail("Should not be able to set TTL using non-numeric values"); } catch (IOException e) { checkShutdownSignal(AMQP.PRECONDITION_FAILED, e); + } catch (ShutdownSignalException e) { + checkShutdownSignal(AMQP.PRECONDITION_FAILED, e); } } @@ -77,16 +80,20 @@ protected void releaseResources() throws IOException { fail("Should not be able to set TTL using non-numeric values"); } catch (IOException e) { checkShutdownSignal(AMQP.PRECONDITION_FAILED, e); + } catch (ShutdownSignalException e) { + checkShutdownSignal(AMQP.PRECONDITION_FAILED, e); } } - @Test public void tTLMustBePositive() throws Exception { + @Test public void tTLMustBePositive() { try { declareAndBindQueue(-10); publishAndSync(MSG[0]); fail("Should not be able to set TTL using negative values"); } catch (IOException e) { checkShutdownSignal(AMQP.PRECONDITION_FAILED, e); + } catch (ShutdownSignalException e) { + checkShutdownSignal(AMQP.PRECONDITION_FAILED, e); } } @@ -105,7 +112,7 @@ protected void releaseResources() throws IOException { Thread.sleep(1000); String what = get(); - assertNull("expected message " + what + " to have been removed", what); + assertNull(what, "expected message " + what + " to have been removed"); } @Test public void publishAndGetWithExpiry() throws Exception { @@ -176,7 +183,7 @@ protected void releaseResources() throws IOException { Thread.sleep(150); openChannel(); - assertNull("Re-queued message not expired", get()); + assertNull(get(), "Re-queued message not expired"); } @Test public void zeroTTLDelivery() throws Exception { diff --git a/src/test/java/com/rabbitmq/client/test/functional/Tables.java b/src/test/java/com/rabbitmq/client/test/functional/Tables.java index 6f8f1854a8..a1e405c7f8 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Tables.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Tables.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,8 +16,8 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.math.BigDecimal; @@ -29,7 +29,7 @@ import java.util.Map; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AMQP.BasicProperties; @@ -87,18 +87,17 @@ private static void assertMapsEqual(Map a, Object va = a.get(k); Object vb = b.get(k); if (va instanceof byte[] && vb instanceof byte[]) { - assertTrue("unequal entry for key " + k, - Arrays.equals((byte[])va, (byte[])vb)); + assertTrue(Arrays.equals((byte[])va, (byte[])vb), "unequal entry for key " + k); } else if (va instanceof List && vb instanceof List) { Iterator vbi = ((List)vb).iterator(); for (Object vaEntry : (List)va) { Object vbEntry = vbi.next(); - assertEquals("arrays unequal at key " + k, vaEntry, vbEntry); + assertEquals(vaEntry, vbEntry, "arrays unequal at key " + k); } } else { - assertEquals("unequal entry for key " + k, va, vb); + assertEquals(va, vb, "unequal entry for key " + k); } } } diff --git a/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryFiltering.java b/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryFiltering.java index 3879359959..1af68242b4 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryFiltering.java +++ b/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryFiltering.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -30,7 +30,7 @@ import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.client.test.TestUtils; import java.util.UUID; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.time.Duration; @@ -40,8 +40,8 @@ import java.util.concurrent.atomic.AtomicInteger; import static com.rabbitmq.client.test.TestUtils.*; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -117,12 +117,12 @@ public void topologyRecoveryFilteringBindings() throws Exception { closeAndWaitForRecovery((RecoverableConnection) c); - assertTrue("The message should have been received by now", sendAndConsumeMessage( + assertTrue(sendAndConsumeMessage( "topology.recovery.exchange", "recovered.binding", "topology.recovery.queue.1", c - )); - assertFalse("Binding shouldn't recover, no messages should have been received", sendAndConsumeMessage( + ), "The message should have been received by now"); + assertFalse(sendAndConsumeMessage( "topology.recovery.exchange", "filtered.binding", "topology.recovery.queue.2", c - )); + ), "Binding shouldn't recover, no messages should have been received"); } @Test @@ -166,8 +166,8 @@ public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProp waitAtMost(Duration.ofSeconds(5), () -> recoveredConsumerMessageCount.get() == initialCount + 1); ch.basicPublish("topology.recovery.exchange", "filtered.consumer", null, "".getBytes()); - assertFalse("Consumer shouldn't recover, no extra messages should have been received", - filteredConsumerLatch.await(5, TimeUnit.SECONDS)); + assertFalse(filteredConsumerLatch.await(5, TimeUnit.SECONDS), + "Consumer shouldn't recover, no extra messages should have been received"); } private static class SimpleTopologyRecoveryFilter implements TopologyRecoveryFilter { diff --git a/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryRetry.java b/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryRetry.java index c8d9c894a9..91a777ad1b 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryRetry.java +++ b/src/test/java/com/rabbitmq/client/test/functional/TopologyRecoveryRetry.java @@ -1,4 +1,4 @@ -// Copyright (c) 2018-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2018-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -27,9 +27,9 @@ import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.client.test.TestUtils; import com.rabbitmq.tools.Host; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.HashMap; import java.util.UUID; @@ -39,7 +39,7 @@ import static com.rabbitmq.client.impl.recovery.TopologyRecoveryRetryLogic.RETRY_ON_QUEUE_NOT_FOUND_RETRY_HANDLER; import static com.rabbitmq.client.test.TestUtils.closeAllConnectionsAndWaitForRecovery; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @@ -48,7 +48,7 @@ public class TopologyRecoveryRetry extends BrokerTestCase { private volatile Consumer backoffConsumer; - @Before + @BeforeEach public void init() { this.backoffConsumer = attempt -> { }; } diff --git a/src/test/java/com/rabbitmq/client/test/functional/Transactions.java b/src/test/java/com/rabbitmq/client/test/functional/Transactions.java index 3e3d66883b..b7890aed45 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/Transactions.java +++ b/src/test/java/com/rabbitmq/client/test/functional/Transactions.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,14 +16,14 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.GetResponse; @@ -324,8 +324,7 @@ private long[] publishSelectAndGet(int n) basicAck(); channel.basicRecover(true); - assertNull("Acked uncommitted message redelivered", - basicGet(true)); + assertNull(basicGet(true), "Acked uncommitted message redelivered"); } @Test public void commitWithDeletedQueue() diff --git a/src/test/java/com/rabbitmq/client/test/functional/UnbindAutoDeleteExchange.java b/src/test/java/com/rabbitmq/client/test/functional/UnbindAutoDeleteExchange.java index 29c4faa2b4..08e0b8fbac 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/UnbindAutoDeleteExchange.java +++ b/src/test/java/com/rabbitmq/client/test/functional/UnbindAutoDeleteExchange.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,11 +15,11 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/functional/UnexpectedFrames.java b/src/test/java/com/rabbitmq/client/test/functional/UnexpectedFrames.java index e028c3cf47..fd36d11026 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/UnexpectedFrames.java +++ b/src/test/java/com/rabbitmq/client/test/functional/UnexpectedFrames.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -22,7 +22,7 @@ import com.rabbitmq.client.impl.recovery.AutorecoveringConnection; import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.net.SocketFactory; import java.io.IOException; diff --git a/src/test/java/com/rabbitmq/client/test/functional/UserIDHeader.java b/src/test/java/com/rabbitmq/client/test/functional/UserIDHeader.java index d776029df5..1f0383fbde 100644 --- a/src/test/java/com/rabbitmq/client/test/functional/UserIDHeader.java +++ b/src/test/java/com/rabbitmq/client/test/functional/UserIDHeader.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,14 +15,14 @@ package com.rabbitmq.client.test.functional; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.AlreadyClosedException; diff --git a/src/test/java/com/rabbitmq/client/test/server/AbsentQueue.java b/src/test/java/com/rabbitmq/client/test/server/AbsentQueue.java index a0e857d828..e304a71db6 100644 --- a/src/test/java/com/rabbitmq/client/test/server/AbsentQueue.java +++ b/src/test/java/com/rabbitmq/client/test/server/AbsentQueue.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,14 +19,17 @@ import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.test.functional.ClusteredTestBase; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.TestInfo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; /** * This tests whether 'absent' queues - durable queues whose home node @@ -36,16 +39,18 @@ public class AbsentQueue extends ClusteredTestBase { private static final String Q = "absent-queue"; - @Override public void setUp() throws IOException, TimeoutException { - super.setUp(); + @BeforeEach + @Override public void setUp(TestInfo info) throws IOException, TimeoutException { + super.setUp(info); if (clusteredConnection != null) stopSecondary(); } - @Override public void tearDown() throws IOException, TimeoutException { + @AfterEach + @Override public void tearDown(TestInfo info) throws IOException, TimeoutException { if (clusteredConnection != null) startSecondary(); - super.tearDown(); + super.tearDown(info); } @Override protected void createResources() throws IOException { @@ -57,7 +62,7 @@ public class AbsentQueue extends ClusteredTestBase { } @Test public void notFound() throws Exception { - if (!HATests.HA_TESTS_RUNNING) { + if (!ha()) { // we don't care about this test in normal mode return; } @@ -73,9 +78,9 @@ protected void assertNotFound(Callable t) throws Exception { if (clusteredChannel == null) return; try { t.call(); - if (!HATests.HA_TESTS_RUNNING) fail("expected not_found"); + if (!ha()) fail("expected not_found"); } catch (IOException ioe) { - assertFalse(HATests.HA_TESTS_RUNNING); + assertFalse(ha()); checkShutdownSignal(AMQP.NOT_FOUND, ioe); channel = connection.createChannel(); } @@ -84,7 +89,7 @@ protected void assertNotFound(Callable t) throws Exception { private void waitPropagationInHa() throws IOException, InterruptedException { // can be necessary to wait a bit in HA mode - if (HATests.HA_TESTS_RUNNING) { + if (ha()) { long waited = 0; while(waited < 5000) { Channel tempChannel = connection.createChannel(); diff --git a/src/test/java/com/rabbitmq/client/test/server/AlternateExchangeEquivalence.java b/src/test/java/com/rabbitmq/client/test/server/AlternateExchangeEquivalence.java index 676dac7015..a978d06a48 100644 --- a/src/test/java/com/rabbitmq/client/test/server/AlternateExchangeEquivalence.java +++ b/src/test/java/com/rabbitmq/client/test/server/AlternateExchangeEquivalence.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,7 +20,7 @@ import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.functional.ExchangeEquivalenceBase; diff --git a/src/test/java/com/rabbitmq/client/test/server/BlockedConnection.java b/src/test/java/com/rabbitmq/client/test/server/BlockedConnection.java index 4856ea151b..a80b12387d 100644 --- a/src/test/java/com/rabbitmq/client/test/server/BlockedConnection.java +++ b/src/test/java/com/rabbitmq/client/test/server/BlockedConnection.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,7 +16,7 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.CountDownLatch; @@ -24,7 +24,7 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.BlockedListener; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/server/Bug19219Test.java b/src/test/java/com/rabbitmq/client/test/server/Bug19219Test.java index e16d40d731..2506ef075a 100644 --- a/src/test/java/com/rabbitmq/client/test/server/Bug19219Test.java +++ b/src/test/java/com/rabbitmq/client/test/server/Bug19219Test.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,14 +15,14 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; diff --git a/src/test/java/com/rabbitmq/client/test/server/ChannelLimitNegotiation.java b/src/test/java/com/rabbitmq/client/test/server/ChannelLimitNegotiation.java index a890f2ca66..a008c5b44d 100644 --- a/src/test/java/com/rabbitmq/client/test/server/ChannelLimitNegotiation.java +++ b/src/test/java/com/rabbitmq/client/test/server/ChannelLimitNegotiation.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,10 +15,10 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.Executors; @@ -27,7 +27,7 @@ import com.rabbitmq.client.impl.recovery.AutorecoveringConnection; import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Connection; diff --git a/src/test/java/com/rabbitmq/client/test/server/DeadLetterExchangeDurable.java b/src/test/java/com/rabbitmq/client/test/server/DeadLetterExchangeDurable.java index 312ce61810..f280408fa8 100644 --- a/src/test/java/com/rabbitmq/client/test/server/DeadLetterExchangeDurable.java +++ b/src/test/java/com/rabbitmq/client/test/server/DeadLetterExchangeDurable.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,13 +15,13 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.util.HashMap; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.MessageProperties; import com.rabbitmq.client.test.BrokerTestCase; @@ -51,7 +51,7 @@ protected void releaseResources() throws IOException { @Test public void deadLetterQueueTTLExpiredWhileDown() throws Exception { // This test is nonsensical (and often breaks) in HA mode. - if (HATests.HA_TESTS_RUNNING) return; + if (ha()) return; for(int x = 0; x < DeadLetterExchange.MSG_COUNT; x++) { channel.basicPublish("amq.direct", "test", MessageProperties.MINIMAL_PERSISTENT_BASIC, "test message".getBytes()); diff --git a/src/test/java/com/rabbitmq/client/test/server/DurableBindingLifecycle.java b/src/test/java/com/rabbitmq/client/test/server/DurableBindingLifecycle.java index 5be557cd3d..0b5d19d529 100644 --- a/src/test/java/com/rabbitmq/client/test/server/DurableBindingLifecycle.java +++ b/src/test/java/com/rabbitmq/client/test/server/DurableBindingLifecycle.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,13 +16,15 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static com.rabbitmq.client.test.TestUtils.waitAtMost; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.test.functional.BindingLifecycleBase; @@ -53,9 +55,9 @@ protected void restart() throws IOException, TimeoutException { } private void restartPrimary() throws IOException, TimeoutException { - tearDown(); + tearDown(this.testInfo); bareRestart(); - setUp(); + setUp(this.testInfo); } /** @@ -71,7 +73,16 @@ private void restartPrimary() throws IOException, TimeoutException { basicPublishVolatile(X, K); } - assertDelivered(Q, N); + AtomicInteger receivedCount = new AtomicInteger(0); + waitAtMost(() -> { + GetResponse r; + r = basicGet(Q); + if (r != null) { + assertThat(r.getEnvelope().isRedeliver()).isFalse(); + receivedCount.incrementAndGet(); + } + return receivedCount.get() == N; + }); deleteQueue(Q); deleteExchange(X); @@ -109,7 +120,7 @@ private void restartPrimary() throws IOException, TimeoutException { } GetResponse response = channel.basicGet(Q, true); - assertNull("The initial response SHOULD BE null", response); + assertNull(response, "The initial response SHOULD BE null"); deleteQueue(Q); deleteExchange(X); @@ -130,8 +141,7 @@ private void restartPrimary() throws IOException, TimeoutException { basicPublishVolatile("", Q); - GetResponse response = channel.basicGet(Q, true); - assertNotNull("The initial response SHOULD NOT be null", response); + waitAtMost(() -> channel.basicGet(Q, true) != null); deleteQueue(Q); } @@ -152,7 +162,15 @@ private void restartPrimary() throws IOException, TimeoutException { restartPrimary(); basicPublishVolatile("transientX", ""); - assertDelivered("durableQ", 1); + waitAtMost(() -> { + GetResponse response = channel.basicGet("durableQ", true); + if (response == null) { + return false; + } else { + assertThat(response.getEnvelope().isRedeliver()).isFalse(); + return true; + } + }); deleteExchange("transientX"); deleteQueue("durableQ"); diff --git a/src/test/java/com/rabbitmq/client/test/server/EffectVisibilityCrossNodeTest.java b/src/test/java/com/rabbitmq/client/test/server/EffectVisibilityCrossNodeTest.java index b4c9a0bc6a..db5d63ef7a 100644 --- a/src/test/java/com/rabbitmq/client/test/server/EffectVisibilityCrossNodeTest.java +++ b/src/test/java/com/rabbitmq/client/test/server/EffectVisibilityCrossNodeTest.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,12 +15,12 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.concurrent.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.test.functional.ClusteredTestBase; @@ -31,16 +31,20 @@ public class EffectVisibilityCrossNodeTest extends ClusteredTestBase { private final String[] queues = new String[QUEUES]; + ExecutorService executorService; + @Override protected void createResources() throws IOException { for (int i = 0; i < queues.length ; i++) { queues[i] = alternateChannel.queueDeclare("", false, false, true, null).getQueue(); alternateChannel.queueBind(queues[i], "amq.fanout", ""); } + executorService = Executors.newSingleThreadExecutor(); } @Override protected void releaseResources() throws IOException { + executorService.shutdownNow(); for (int i = 0; i < queues.length ; i++) { alternateChannel.queueDelete(queues[i]); } @@ -53,24 +57,33 @@ protected void releaseResources() throws IOException { private static final byte[] msg = "".getBytes(); @Test public void effectVisibility() throws Exception { - ExecutorService executorService = Executors.newSingleThreadExecutor(); - try { - Future task = executorService.submit(() -> { - for (int i = 0; i < BATCHES; i++) { - Thread.sleep(10); // to avoid flow control for the connection - for (int j = 0; j < MESSAGES_PER_BATCH; j++) { - channel.basicPublish("amq.fanout", "", null, msg); - } - for (int j = 0; j < queues.length; j++) { - assertEquals(MESSAGES_PER_BATCH, channel.queuePurge(queues[j]).getMessageCount()); + // the test bulk is asynchronous because this test has a history of hanging + Future task = + executorService.submit( + () -> { + for (int i = 0; i < BATCHES; i++) { + Thread.sleep(10); // to avoid flow control for the connection + for (int j = 0; j < MESSAGES_PER_BATCH; j++) { + channel.basicPublish("amq.fanout", "", null, msg); + } + for (int j = 0; j < queues.length; j++) { + String queue = queues[j]; + long timeout = 10 * 1000; + long waited = 0; + int purged = 0; + while (waited < timeout) { + purged += channel.queuePurge(queue).getMessageCount(); + if (purged == MESSAGES_PER_BATCH) { + break; } + Thread.sleep(10); + waited += 10; + } + assertEquals(MESSAGES_PER_BATCH, purged, "Queue " + queue + " should have been purged after 10 seconds"); } - return null; + } + return null; }); task.get(1, TimeUnit.MINUTES); - } finally { - executorService.shutdownNow(); - executorService.awaitTermination(1, TimeUnit.SECONDS); - } } } diff --git a/src/test/java/com/rabbitmq/client/test/server/ExclusiveQueueDurability.java b/src/test/java/com/rabbitmq/client/test/server/ExclusiveQueueDurability.java index 2be62c3c9e..6671be803c 100644 --- a/src/test/java/com/rabbitmq/client/test/server/ExclusiveQueueDurability.java +++ b/src/test/java/com/rabbitmq/client/test/server/ExclusiveQueueDurability.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,12 +16,13 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.fail; +import static com.rabbitmq.client.test.TestUtils.safeDelete; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; @@ -41,8 +42,7 @@ protected boolean isAutomaticRecoveryEnabled() { return false; } - void verifyQueueMissing(Channel channel, String queueName) - throws IOException { + void verifyQueueMissing(Channel channel, String queueName) { try { channel.queueDeclare(queueName, false, false, false, null); } catch (IOException ioe) { @@ -54,16 +54,22 @@ void verifyQueueMissing(Channel channel, String queueName) // 1) connection and queue are on same node, node restarts -> queue // should no longer exist @Test public void connectionQueueSameNode() throws Exception { - channel.queueDeclare("scenario1", true, true, false, null); - restartPrimaryAbruptly(); - verifyQueueMissing(channel, "scenario1"); + String queueName = generateQueueName(); + safeDelete(connection, queueName); + try { + channel.queueDeclare(queueName, true, true, false, null); + restartPrimaryAbruptly(); + verifyQueueMissing(channel, queueName); + } finally { + safeDelete(connection, queueName); + } } private void restartPrimaryAbruptly() throws IOException, TimeoutException { connection = null; channel = null; bareRestart(); - setUp(); + setUp(this.testInfo); } /* @@ -80,4 +86,5 @@ private void restartPrimaryAbruptly() throws IOException, TimeoutException { * tied to nodes, so one can't engineer a situation in which a connection * and its exclusive queue are on different nodes. */ + } diff --git a/src/test/java/com/rabbitmq/client/test/server/Firehose.java b/src/test/java/com/rabbitmq/client/test/server/Firehose.java index 28064a1383..63389b5384 100644 --- a/src/test/java/com/rabbitmq/client/test/server/Firehose.java +++ b/src/test/java/com/rabbitmq/client/test/server/Firehose.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,15 +15,15 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/server/HATests.java b/src/test/java/com/rabbitmq/client/test/server/HATests.java deleted file mode 100644 index d4078c4ac2..0000000000 --- a/src/test/java/com/rabbitmq/client/test/server/HATests.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. -// -// This software, the RabbitMQ Java client library, is triple-licensed under the -// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 -// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see -// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, -// please see LICENSE-APACHE2. -// -// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, -// either express or implied. See the LICENSE file for specific language governing -// rights and limitations of this software. -// -// If you have any questions regarding licensing, please contact us at -// info@rabbitmq.com. - -package com.rabbitmq.client.test.server; - -import com.rabbitmq.client.test.AbstractRMQTestSuite; -import com.rabbitmq.client.test.RequiredPropertiesSuite; -import com.rabbitmq.client.test.functional.FunctionalTests; -import com.rabbitmq.tools.Host; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(RequiredPropertiesSuite.class) -@Suite.SuiteClasses({ - HATests.SetUp.class, - FunctionalTests.class, - ServerTests.class, - HATests.TearDown.class -}) -public class HATests { - - // initialize system properties - static{ - new AbstractRMQTestSuite(){}; - } - - // this is horrific - public static boolean HA_TESTS_RUNNING = false; - - // This is of course an abuse of the TestCase concept - but I don't want to - // run this command on every test case. And there's no hook for "before / - // after this test suite". - public static class SetUp { - - @Test public void setUp() throws Exception { - Host.rabbitmqctl("set_policy HA '.*' '{\"ha-mode\":\"all\"}'"); - HA_TESTS_RUNNING = true; - } - - @Test public void testNothing() {} - } - - public static class TearDown { - - @Test public void tearDown() throws Exception { - Host.rabbitmqctl("clear_policy HA"); - HA_TESTS_RUNNING = false; - } - - @Test public void testNothing() {} - } -} diff --git a/src/test/java/com/rabbitmq/client/test/server/HaTestSuite.java b/src/test/java/com/rabbitmq/client/test/server/HaTestSuite.java new file mode 100644 index 0000000000..12f88c6612 --- /dev/null +++ b/src/test/java/com/rabbitmq/client/test/server/HaTestSuite.java @@ -0,0 +1,30 @@ +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client.test.server; + +import com.rabbitmq.client.test.functional.FunctionalTestSuite; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + FunctionalTestSuite.class, + ServerTestSuite.class, + LastHaTestSuite.class, +}) +public class HaTestSuite { + +} diff --git a/src/test/java/com/rabbitmq/client/test/server/LastHaTestSuite.java b/src/test/java/com/rabbitmq/client/test/server/LastHaTestSuite.java new file mode 100644 index 0000000000..12aa495ae0 --- /dev/null +++ b/src/test/java/com/rabbitmq/client/test/server/LastHaTestSuite.java @@ -0,0 +1,37 @@ +// Copyright (c) 2023 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client.test.server; + +import com.rabbitmq.client.test.server.LastHaTestSuite.DummyTest; +import org.junit.jupiter.api.Test; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +/** + * Marker test suite to signal the end of the HA test suite. + */ +@Suite +@SelectClasses(DummyTest.class) +public class LastHaTestSuite { + + static class DummyTest { + @Test + void noOp() { + + } + } + +} diff --git a/src/test/java/com/rabbitmq/client/test/server/LoopbackUsers.java b/src/test/java/com/rabbitmq/client/test/server/LoopbackUsers.java index a1e26b3d1b..e758b65c9e 100644 --- a/src/test/java/com/rabbitmq/client/test/server/LoopbackUsers.java +++ b/src/test/java/com/rabbitmq/client/test/server/LoopbackUsers.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.net.Inet4Address; @@ -26,9 +26,9 @@ import java.util.concurrent.TimeoutException; import com.rabbitmq.client.test.TestUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AuthenticationFailureException; import com.rabbitmq.client.ConnectionFactory; @@ -36,12 +36,12 @@ public class LoopbackUsers { - @Before public void setUp() throws IOException { + @BeforeEach public void setUp() throws IOException { Host.rabbitmqctl("add_user test test"); Host.rabbitmqctl("set_permissions test '.*' '.*' '.*'"); } - @After public void tearDown() throws IOException { + @AfterEach public void tearDown() throws IOException { Host.rabbitmqctl("delete_user test"); } diff --git a/src/test/java/com/rabbitmq/client/test/server/MemoryAlarms.java b/src/test/java/com/rabbitmq/client/test/server/MemoryAlarms.java index 690a77ddcd..d6be4534de 100644 --- a/src/test/java/com/rabbitmq/client/test/server/MemoryAlarms.java +++ b/src/test/java/com/rabbitmq/client/test/server/MemoryAlarms.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,18 +15,21 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import java.io.IOException; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.test.BrokerTestCase; +import org.junit.jupiter.api.TestInfo; public class MemoryAlarms extends BrokerTestCase { @@ -35,18 +38,20 @@ public class MemoryAlarms extends BrokerTestCase { private Connection connection2; private Channel channel2; + @BeforeEach @Override - public void setUp() throws IOException, TimeoutException { + public void setUp(TestInfo info) throws IOException, TimeoutException { connectionFactory.setRequestedHeartbeat(1); - super.setUp(); + super.setUp(info); if (connection2 == null) { connection2 = connectionFactory.newConnection(); } channel2 = connection2.createChannel(); } + @AfterEach @Override - public void tearDown() throws IOException, TimeoutException { + public void tearDown(TestInfo info) throws IOException, TimeoutException { clearAllResourceAlarms(); if (channel2 != null) { channel2.abort(); @@ -56,7 +61,7 @@ public void tearDown() throws IOException, TimeoutException { connection2.abort(); connection2 = null; } - super.tearDown(); + super.tearDown(info); connectionFactory.setRequestedHeartbeat(0); } diff --git a/src/test/java/com/rabbitmq/client/test/server/MessageRecovery.java b/src/test/java/com/rabbitmq/client/test/server/MessageRecovery.java index f59e4ced96..c17ef018c9 100644 --- a/src/test/java/com/rabbitmq/client/test/server/MessageRecovery.java +++ b/src/test/java/com/rabbitmq/client/test/server/MessageRecovery.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,12 +17,12 @@ import java.io.IOException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.MessageProperties; import com.rabbitmq.client.test.ConfirmBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class MessageRecovery extends ConfirmBase { @@ -56,7 +56,7 @@ public class MessageRecovery extends ConfirmBase // with slave(s). // NB: this wont work when running against a single node broker // and running the test individually outside of the HA suite - boolean expectDelivered = HATests.HA_TESTS_RUNNING; + boolean expectDelivered = ha(); try { channel.queueDeclarePassive(Q2); channel.queueDelete(Q2); diff --git a/src/test/java/com/rabbitmq/client/test/server/Permissions.java b/src/test/java/com/rabbitmq/client/test/server/Permissions.java index c67d0cc0c6..2204f9c9ce 100644 --- a/src/test/java/com/rabbitmq/client/test/server/Permissions.java +++ b/src/test/java/com/rabbitmq/client/test/server/Permissions.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -22,14 +22,17 @@ import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.client.test.TestUtils; import com.rabbitmq.tools.Host; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.TestInfo; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class Permissions extends BrokerTestCase { @@ -45,16 +48,20 @@ public Permissions() connectionFactory = factory; } - public void setUp() + @BeforeEach + @Override + public void setUp(TestInfo info) throws IOException, TimeoutException { deleteRestrictedAccount(); addRestrictedAccount(); - super.setUp(); + super.setUp(info); } - public void tearDown() + @AfterEach + @Override + public void tearDown(TestInfo info) throws IOException, TimeoutException { - super.tearDown(); + super.tearDown(info); deleteRestrictedAccount(); } @@ -124,8 +131,7 @@ protected void withNames(WithName action) } catch (IOException e) { assertTrue(e instanceof AuthenticationFailureException); String msg = e.getMessage(); - assertTrue("Exception message should contain 'auth'", - msg.toLowerCase().contains("auth")); + assertTrue(msg.toLowerCase().contains("auth"), "Exception message should contain 'auth'"); } } @@ -366,13 +372,13 @@ protected void runTest(boolean exp, String name, WithName test) String msg = "'" + name + "' -> " + exp; try { test.with(name); - assertTrue(msg, exp); + assertTrue(exp, msg); } catch (IOException e) { - assertFalse(msg, exp); + assertFalse(exp, msg); checkShutdownSignal(AMQP.ACCESS_REFUSED, e); openChannel(); } catch (AlreadyClosedException e) { - assertFalse(msg, exp); + assertFalse(exp, msg); checkShutdownSignal(AMQP.ACCESS_REFUSED, e); openChannel(); } diff --git a/src/test/java/com/rabbitmq/client/test/server/PersistenceGuarantees.java b/src/test/java/com/rabbitmq/client/test/server/PersistenceGuarantees.java index 69bc8093b4..e0547ca786 100644 --- a/src/test/java/com/rabbitmq/client/test/server/PersistenceGuarantees.java +++ b/src/test/java/com/rabbitmq/client/test/server/PersistenceGuarantees.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,12 +15,12 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import com.rabbitmq.client.impl.nio.NioParams; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.MessageProperties; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/server/PriorityQueues.java b/src/test/java/com/rabbitmq/client/test/server/PriorityQueues.java index 76c34dbbeb..1fba1684d7 100644 --- a/src/test/java/com/rabbitmq/client/test/server/PriorityQueues.java +++ b/src/test/java/com/rabbitmq/client/test/server/PriorityQueues.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,8 +15,8 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.ArrayList; @@ -27,7 +27,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.DefaultConsumer; diff --git a/src/test/java/com/rabbitmq/client/test/server/ServerTests.java b/src/test/java/com/rabbitmq/client/test/server/ServerTestSuite.java similarity index 69% rename from src/test/java/com/rabbitmq/client/test/server/ServerTests.java rename to src/test/java/com/rabbitmq/client/test/server/ServerTestSuite.java index a532586e40..c850a31faf 100644 --- a/src/test/java/com/rabbitmq/client/test/server/ServerTests.java +++ b/src/test/java/com/rabbitmq/client/test/server/ServerTestSuite.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,14 +16,12 @@ package com.rabbitmq.client.test.server; -import com.rabbitmq.client.test.AbstractRMQTestSuite; -import com.rabbitmq.client.test.RequiredPropertiesSuite; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; -@RunWith(RequiredPropertiesSuite.class) -@Suite.SuiteClasses({ - Permissions.class, +@Suite +@SelectClasses({ + Permissions.class, DurableBindingLifecycle.class, DeadLetterExchangeDurable.class, EffectVisibilityCrossNodeTest.class, @@ -38,15 +36,10 @@ BlockedConnection.class, ChannelLimitNegotiation.class, LoopbackUsers.class, - XDeathHeaderGrowth.class, - PriorityQueues.class, - TopicPermissions.class + XDeathHeaderGrowth.class, + PriorityQueues.class, + TopicPermissions.class }) -public class ServerTests { - - // initialize system properties - static{ - new AbstractRMQTestSuite(){}; - } +public class ServerTestSuite { } diff --git a/src/test/java/com/rabbitmq/client/test/server/Shutdown.java b/src/test/java/com/rabbitmq/client/test/server/Shutdown.java index 8d7194bd38..9e861bdc9e 100644 --- a/src/test/java/com/rabbitmq/client/test/server/Shutdown.java +++ b/src/test/java/com/rabbitmq/client/test/server/Shutdown.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,7 +15,7 @@ package com.rabbitmq.client.test.server; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.test.BrokerTestCase; diff --git a/src/test/java/com/rabbitmq/client/test/server/TopicPermissions.java b/src/test/java/com/rabbitmq/client/test/server/TopicPermissions.java index 5b79de1387..d48f6ea952 100644 --- a/src/test/java/com/rabbitmq/client/test/server/TopicPermissions.java +++ b/src/test/java/com/rabbitmq/client/test/server/TopicPermissions.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -20,41 +20,50 @@ import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.test.BrokerTestCase; import com.rabbitmq.tools.Host; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.TimeoutException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; public class TopicPermissions extends BrokerTestCase { + private static final Logger LOGGER = LoggerFactory.getLogger(TopicPermissions.class); + String protectedTopic = "protected.topic"; String notProtectedTopic = "not.protected.topic"; String noneTopicExchange = "not.a.topic"; @Override protected boolean shouldRun() throws IOException { + LOGGER.debug("Checking if test should run"); return Host.isRabbitMqCtlCommandAvailable("set_topic_permissions"); } @Override protected void createResources() throws IOException, TimeoutException { + LOGGER.debug("Creating AMQP resources"); channel.exchangeDeclare(protectedTopic, BuiltinExchangeType.TOPIC); channel.exchangeDeclare(notProtectedTopic, BuiltinExchangeType.TOPIC); channel.exchangeDeclare(noneTopicExchange, BuiltinExchangeType.DIRECT); + LOGGER.debug("Setting permissions"); Host.rabbitmqctl("set_topic_permissions -p / guest " + protectedTopic + " \"^{username}\" \"^{username}\""); Host.rabbitmqctl("set_topic_permissions -p / guest " + noneTopicExchange + " \"^{username}\" \"^{username}\""); } @Override protected void releaseResources() throws IOException { + LOGGER.debug("Deleting AMQP resources"); channel.exchangeDelete(protectedTopic); channel.exchangeDelete(notProtectedTopic); channel.exchangeDelete(noneTopicExchange); + LOGGER.debug("Clearing permissions"); Host.rabbitmqctl("clear_topic_permissions -p / guest"); } @@ -107,14 +116,18 @@ public void topicPermissions() throws IOException { } void assertAccessOk(String description, Callable action) { + LOGGER.debug("Running '" + description + "'"); try { action.call(); } catch(Exception e) { fail(description + " (" + e.getMessage()+")"); + } finally { + LOGGER.debug("'" + description + "' done"); } } void assertAccessRefused(String description, Callable action) throws IOException { + LOGGER.debug("Running '" + description + "'"); try { action.call(); fail(description); @@ -126,6 +139,8 @@ void assertAccessRefused(String description, Callable action) throws IOExc openChannel(); } catch(Exception e) { fail("Unexpected exception: " + e.getMessage()); + } finally { + LOGGER.debug("'" + description + "' done"); } } } diff --git a/src/test/java/com/rabbitmq/client/test/server/XDeathHeaderGrowth.java b/src/test/java/com/rabbitmq/client/test/server/XDeathHeaderGrowth.java index fb65d954b3..0a0537330d 100644 --- a/src/test/java/com/rabbitmq/client/test/server/XDeathHeaderGrowth.java +++ b/src/test/java/com/rabbitmq/client/test/server/XDeathHeaderGrowth.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,8 +15,8 @@ package com.rabbitmq.client.test.server; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.ArrayList; @@ -30,7 +30,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; diff --git a/src/test/java/com/rabbitmq/client/test/ssl/BadVerifiedConnection.java b/src/test/java/com/rabbitmq/client/test/ssl/BadVerifiedConnection.java index 9137213578..748bb9f883 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/BadVerifiedConnection.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/BadVerifiedConnection.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,68 +15,31 @@ package com.rabbitmq.client.test.ssl; -import com.rabbitmq.client.test.TestUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.TrustManagerFactory; -import java.io.FileInputStream; import java.io.IOException; -import java.security.*; -import java.security.cert.CertificateException; import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for bug 19356 - SSL Support in rabbitmq * */ +@EnabledForJreRange(min = JRE.JAVA_11) public class BadVerifiedConnection extends UnverifiedConnection { + public void openConnection() throws IOException, TimeoutException { try { - String keystorePath = System.getProperty("test-keystore.empty"); - assertNotNull(keystorePath); - String keystorePasswd = System.getProperty("test-keystore.password"); - assertNotNull(keystorePasswd); - char [] keystorePassword = keystorePasswd.toCharArray(); - - KeyStore tks = KeyStore.getInstance("JKS"); - tks.load(new FileInputStream(keystorePath), keystorePassword); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(tks); - - String p12Path = System.getProperty("test-client-cert.path"); - assertNotNull(p12Path); - String p12Passwd = System.getProperty("test-client-cert.password"); - assertNotNull(p12Passwd); - KeyStore ks = KeyStore.getInstance("PKCS12"); - char [] p12Password = p12Passwd.toCharArray(); - ks.load(new FileInputStream(p12Path), p12Password); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, p12Password); - - SSLContext c = getSSLContext(); - c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - - connectionFactory = TestUtils.connectionFactory(); + SSLContext c = TlsTestUtils.badVerifiedSslContext(); connectionFactory.useSslProtocol(c); - } catch (NoSuchAlgorithmException ex) { - throw new IOException(ex.toString()); - } catch (KeyManagementException ex) { - throw new IOException(ex.toString()); - } catch (KeyStoreException ex) { - throw new IOException(ex.toString()); - } catch (CertificateException ex) { - throw new IOException(ex.toString()); - } catch (UnrecoverableKeyException ex) { - throw new IOException(ex.toString()); + } catch (Exception ex) { + throw new IOException(ex); } try { diff --git a/src/test/java/com/rabbitmq/client/test/ssl/ConnectionFactoryDefaultTlsVersion.java b/src/test/java/com/rabbitmq/client/test/ssl/ConnectionFactoryDefaultTlsVersion.java index dde98277d4..1a03a02420 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/ConnectionFactoryDefaultTlsVersion.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/ConnectionFactoryDefaultTlsVersion.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -16,28 +16,27 @@ package com.rabbitmq.client.test.ssl; import com.rabbitmq.client.ConnectionFactory; -import junit.framework.TestCase; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ConnectionFactoryDefaultTlsVersion { @Test public void defaultTlsVersionJdk16ShouldTakeFallback() { String [] supportedProtocols = {"SSLv2Hello", "SSLv3", "TLSv1"}; String tlsProtocol = ConnectionFactory.computeDefaultTlsProtocol(supportedProtocols); - Assert.assertEquals("TLSv1",tlsProtocol); + Assertions.assertEquals("TLSv1",tlsProtocol); } @Test public void defaultTlsVersionJdk17ShouldTakePrefered() { String [] supportedProtocols = {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; String tlsProtocol = ConnectionFactory.computeDefaultTlsProtocol(supportedProtocols); - Assert.assertEquals("TLSv1.2",tlsProtocol); + Assertions.assertEquals("TLSv1.2",tlsProtocol); } @Test public void defaultTlsVersionJdk18ShouldTakePrefered() { String [] supportedProtocols = {"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}; String tlsProtocol = ConnectionFactory.computeDefaultTlsProtocol(supportedProtocols); - Assert.assertEquals("TLSv1.2",tlsProtocol); + Assertions.assertEquals("TLSv1.2",tlsProtocol); } } diff --git a/src/test/java/com/rabbitmq/client/test/ssl/HostnameVerification.java b/src/test/java/com/rabbitmq/client/test/ssl/HostnameVerification.java index 014c02cfdd..f8febe4614 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/HostnameVerification.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/HostnameVerification.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -19,33 +19,25 @@ import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.test.TestUtils; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.TrustManagerFactory; -import java.io.FileInputStream; -import java.security.KeyStore; import java.util.function.Consumer; -import static com.rabbitmq.client.test.TestUtils.getSSLContext; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; -@RunWith(Parameterized.class) +@EnabledForJreRange(min = JRE.JAVA_11) public class HostnameVerification { static SSLContext sslContext; - @Parameterized.Parameter - public Consumer customizer; - @Parameterized.Parameters public static Object[] data() { return new Object[] { blockingIo(enableHostnameVerification()), @@ -71,48 +63,26 @@ private static Consumer enableHostnameVerification() { return connectionFactory -> connectionFactory.enableHostnameVerification(); } - @BeforeClass + @BeforeAll public static void initCrypto() throws Exception { - String keystorePath = System.getProperty("test-keystore.ca"); - assertNotNull(keystorePath); - String keystorePasswd = System.getProperty("test-keystore.password"); - assertNotNull(keystorePasswd); - char[] keystorePassword = keystorePasswd.toCharArray(); - - KeyStore tks = KeyStore.getInstance("JKS"); - tks.load(new FileInputStream(keystorePath), keystorePassword); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(tks); - - String p12Path = System.getProperty("test-client-cert.path"); - assertNotNull(p12Path); - String p12Passwd = System.getProperty("test-client-cert.password"); - assertNotNull(p12Passwd); - - KeyStore ks = KeyStore.getInstance("PKCS12"); - char[] p12Password = p12Passwd.toCharArray(); - ks.load(new FileInputStream(p12Path), p12Password); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, p12Password); - - sslContext = getSSLContext(); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + sslContext = TlsTestUtils.verifiedSslContext(); } - @Test(expected = SSLHandshakeException.class) - public void hostnameVerificationFailsBecauseCertificateNotIssuedForLoopbackInterface() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void hostnameVerificationFailsBecauseCertificateNotIssuedForLoopbackInterface(Consumer customizer) throws Exception { ConnectionFactory connectionFactory = TestUtils.connectionFactory(); connectionFactory.useSslProtocol(sslContext); customizer.accept(connectionFactory); - connectionFactory.newConnection( - () -> singletonList(new Address("127.0.0.1", ConnectionFactory.DEFAULT_AMQP_OVER_SSL_PORT))); - fail("The server certificate isn't issued for 127.0.0.1, the TLS handshake should have failed"); + Assertions.assertThatThrownBy(() -> connectionFactory.newConnection( + () -> singletonList(new Address("127.0.0.1", ConnectionFactory.DEFAULT_AMQP_OVER_SSL_PORT)))) + .isInstanceOf(SSLHandshakeException.class) + .as("The server certificate isn't issued for 127.0.0.1, the TLS handshake should have failed"); } - @Test - public void hostnameVerificationSucceeds() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void hostnameVerificationSucceeds(Consumer customizer) throws Exception { ConnectionFactory connectionFactory = TestUtils.connectionFactory(); connectionFactory.useSslProtocol(sslContext); customizer.accept(connectionFactory); diff --git a/src/test/java/com/rabbitmq/client/test/ssl/NioTlsUnverifiedConnection.java b/src/test/java/com/rabbitmq/client/test/ssl/NioTlsUnverifiedConnection.java index 29fe35899e..884ca4db9a 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/NioTlsUnverifiedConnection.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/NioTlsUnverifiedConnection.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,21 +15,38 @@ package com.rabbitmq.client.test.ssl; -import com.rabbitmq.client.*; +import static com.rabbitmq.client.test.TestUtils.basicGetBasicConsume; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; +import com.rabbitmq.client.TrustEverythingTrustManager; import com.rabbitmq.client.impl.nio.NioParams; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -import javax.net.ssl.SSLEngine; +import com.rabbitmq.client.test.TestUtils; import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; +import java.util.Collection; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; +import javax.net.ssl.TrustManager; +import org.junit.jupiter.api.Test; +import org.netcrusher.core.reactor.NioReactor; +import org.netcrusher.tcp.TcpCrusher; +import org.netcrusher.tcp.TcpCrusherBuilder; +import org.slf4j.LoggerFactory; /** * @@ -73,7 +90,34 @@ public void connectionGetConsume() throws Exception { CountDownLatch latch = new CountDownLatch(1); basicGetBasicConsume(connection, QUEUE, latch, 100 * 1000); boolean messagesReceived = latch.await(5, TimeUnit.SECONDS); - assertTrue("Message has not been received", messagesReceived); + assertTrue(messagesReceived, "Message has not been received"); + } + + @Test + public void connectionGetConsumeProtocols() throws Exception { + Collection availableProtocols = TlsTestUtils.availableTlsProtocols(); + Collection protocols = Stream.of("TLSv1.2", "TLSv1.3") + .filter(p -> availableProtocols.contains(p)) + .collect(Collectors.toList()); + for (String protocol : protocols) { + SSLContext sslContext = SSLContext.getInstance(protocol); + sslContext.init(null, new TrustManager[] {new TrustEverythingTrustManager()}, null); + ConnectionFactory cf = TestUtils.connectionFactory(); + cf.useSslProtocol(sslContext); + cf.useNio(); + AtomicReference engine = new AtomicReference<>(); + NioParams nioParams = new NioParams(); + nioParams.setSslEngineConfigurator(sslEngine -> engine.set(sslEngine)); + cf.setNioParams(nioParams); + try (Connection c = cf.newConnection()) { + CountDownLatch latch = new CountDownLatch(1); + basicGetBasicConsume(c, QUEUE, latch, 100); + boolean messagesReceived = latch.await(5, TimeUnit.SECONDS); + assertTrue(messagesReceived, "Message has not been received"); + assertThat(engine.get()).isNotNull(); + assertThat(engine.get().getEnabledProtocols()).contains(protocol); + } + } } @Test public void socketChannelConfigurator() throws Exception { @@ -89,7 +133,7 @@ public void connectionGetConsume() throws Exception { Connection connection = null; try { connection = connectionFactory.newConnection(); - assertTrue("The SSL engine configurator should have called", sslEngineHasBeenCalled.get()); + assertTrue(sslEngineHasBeenCalled.get(), "The SSL engine configurator should have called"); } finally { if (connection != null) { connection.close(); @@ -113,34 +157,63 @@ public void connectionGetConsume() throws Exception { } } - private void sendAndVerifyMessage(int size) throws Exception { - CountDownLatch latch = new CountDownLatch(1); - boolean messageReceived = basicGetBasicConsume(connection, QUEUE, latch, size); - assertTrue("Message has not been received", messageReceived); - } + @Test + public void connectionShouldEnforceConnectionTimeout() throws Exception { + int amqpPort = 5671; // assumes RabbitMQ server running on localhost; + int amqpProxyPort = TestUtils.randomNetworkPort(); + + int connectionTimeout = 3_000; + int handshakeTimeout = 1_000; - private boolean basicGetBasicConsume(Connection connection, String queue, final CountDownLatch latch, int msgSize) - throws Exception { - Channel channel = connection.createChannel(); - channel.queueDeclare(queue, false, false, false, null); - channel.queuePurge(queue); + try (NioReactor reactor = new NioReactor(); + TcpCrusher tcpProxy = + TcpCrusherBuilder.builder() + .withReactor(reactor) + .withBindAddress(new InetSocketAddress(amqpProxyPort)) + .withConnectAddress("localhost", amqpPort) + .build()) { - channel.basicPublish("", queue, null, new byte[msgSize]); + tcpProxy.open(); + tcpProxy.freeze(); - String tag = channel.basicConsume(queue, false, new DefaultConsumer(channel) { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + factory.setPort(amqpProxyPort); - @Override - public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { - getChannel().basicAck(envelope.getDeliveryTag(), false); + factory.useSslProtocol(); + factory.useNio(); + + factory.setConnectionTimeout(connectionTimeout); + factory.setHandshakeTimeout(handshakeTimeout); + + ExecutorService executorService = Executors.newSingleThreadExecutor(); + try { + CountDownLatch latch = new CountDownLatch(1); + executorService.submit( + () -> { + try { + factory.newConnection(); latch.countDown(); - } - }); + } catch (SocketTimeoutException e) { + latch.countDown(); + } catch (Exception e) { + // not supposed to happen + } + }); - boolean messageReceived = latch.await(20, TimeUnit.SECONDS); + boolean connectionCreatedTimedOut = latch.await(10, TimeUnit.SECONDS); + assertThat(connectionCreatedTimedOut).isTrue(); - channel.basicCancel(tag); + } finally { + executorService.shutdownNow(); + } + } + } - return messageReceived; + private void sendAndVerifyMessage(int size) throws Exception { + CountDownLatch latch = new CountDownLatch(1); + boolean messageReceived = basicGetBasicConsume(connection, QUEUE, latch, size); + assertTrue(messageReceived, "Message has not been received"); } } diff --git a/src/test/java/com/rabbitmq/client/test/ssl/SSLTests.java b/src/test/java/com/rabbitmq/client/test/ssl/SSLTests.java deleted file mode 100644 index 3d629d15ea..0000000000 --- a/src/test/java/com/rabbitmq/client/test/ssl/SSLTests.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. -// -// This software, the RabbitMQ Java client library, is triple-licensed under the -// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 -// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see -// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, -// please see LICENSE-APACHE2. -// -// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, -// either express or implied. See the LICENSE file for specific language governing -// rights and limitations of this software. -// -// If you have any questions regarding licensing, please contact us at -// info@rabbitmq.com. - - -package com.rabbitmq.client.test.ssl; - -import com.rabbitmq.client.test.AbstractRMQTestSuite; -import com.rabbitmq.client.test.SslContextFactoryTest; -import org.junit.runner.RunWith; -import org.junit.runner.Runner; -import org.junit.runners.Suite; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; - -import java.util.ArrayList; -import java.util.List; - -@RunWith(SSLTests.SslSuite.class) -@Suite.SuiteClasses({ - UnverifiedConnection.class, - VerifiedConnection.class, - BadVerifiedConnection.class, - ConnectionFactoryDefaultTlsVersion.class, - NioTlsUnverifiedConnection.class, - HostnameVerification.class, - TlsConnectionLogging.class, - SslContextFactoryTest.class -}) -public class SSLTests { - - // initialize system properties - static{ - new AbstractRMQTestSuite(){}; - } - - public static class SslSuite extends Suite { - - public SslSuite(Class klass, RunnerBuilder builder) throws InitializationError { - super(klass, builder); - } - - public SslSuite(RunnerBuilder builder, Class[] classes) throws InitializationError { - super(builder, classes); - } - - protected SslSuite(Class klass, Class[] suiteClasses) throws InitializationError { - super(klass, suiteClasses); - } - - protected SslSuite(RunnerBuilder builder, Class klass, Class[] suiteClasses) throws InitializationError { - super(builder, klass, suiteClasses); - } - - protected SslSuite(Class klass, List runners) throws InitializationError { - super(klass, runners); - } - - @Override - protected List getChildren() { - if(!AbstractRMQTestSuite.requiredProperties() && !AbstractRMQTestSuite.isSSLAvailable()) { - return new ArrayList(); - } else { - return super.getChildren(); - } - } - } - -} diff --git a/src/test/java/com/rabbitmq/client/test/ssl/SslTestSuite.java b/src/test/java/com/rabbitmq/client/test/ssl/SslTestSuite.java new file mode 100644 index 0000000000..05160db0f9 --- /dev/null +++ b/src/test/java/com/rabbitmq/client/test/ssl/SslTestSuite.java @@ -0,0 +1,37 @@ +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + + +package com.rabbitmq.client.test.ssl; + +import com.rabbitmq.client.test.SslContextFactoryTest; + +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + UnverifiedConnection.class, + VerifiedConnection.class, + BadVerifiedConnection.class, + ConnectionFactoryDefaultTlsVersion.class, + NioTlsUnverifiedConnection.class, + HostnameVerification.class, + TlsConnectionLogging.class, + SslContextFactoryTest.class +}) +public class SslTestSuite { + +} diff --git a/src/test/java/com/rabbitmq/client/test/ssl/TlsConnectionLogging.java b/src/test/java/com/rabbitmq/client/test/ssl/TlsConnectionLogging.java index 49b9ac3ad9..81360a3815 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/TlsConnectionLogging.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/TlsConnectionLogging.java @@ -1,4 +1,4 @@ -// Copyright (c) 2019-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2019-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -21,9 +21,8 @@ import com.rabbitmq.client.impl.nio.NioParams; import com.rabbitmq.client.test.TestUtils; import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import javax.net.ssl.*; import java.security.cert.X509Certificate; @@ -31,16 +30,11 @@ import java.util.function.Function; import java.util.function.Supplier; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; -@RunWith(Parameterized.class) public class TlsConnectionLogging { - @Parameterized.Parameter - public Function> configurer; - - @Parameterized.Parameters - public static Object[] data() { + public static Object[] certificateInfoAreProperlyExtracted() { return new Object[]{blockingIo(), nio()}; } @@ -64,9 +58,10 @@ public static Function> nio() { }; } - @Test - public void certificateInfoAreProperlyExtracted() throws Exception { - SSLContext sslContext = TestUtils.getSSLContext(); + @ParameterizedTest + @MethodSource + public void certificateInfoAreProperlyExtracted(Function> configurer) throws Exception { + SSLContext sslContext = TlsTestUtils.getSSLContext(); sslContext.init(null, new TrustManager[]{new AlwaysTrustTrustManager()}, null); ConnectionFactory connectionFactory = TestUtils.connectionFactory(); connectionFactory.useSslProtocol(sslContext); diff --git a/src/test/java/com/rabbitmq/client/test/ssl/TlsTestUtils.java b/src/test/java/com/rabbitmq/client/test/ssl/TlsTestUtils.java new file mode 100644 index 0000000000..51702c4a6e --- /dev/null +++ b/src/test/java/com/rabbitmq/client/test/ssl/TlsTestUtils.java @@ -0,0 +1,127 @@ +// Copyright (c) 2021 VMware, Inc. or its affiliates. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.rabbitmq.client.test.ssl; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.FileInputStream; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + +class TlsTestUtils { + + private TlsTestUtils() {} + + static SSLContext badVerifiedSslContext() throws Exception { + return verifiedSslContext(() -> getSSLContext(), emptyKeystoreCa()); + } + + static SSLContext verifiedSslContext() throws Exception { + return verifiedSslContext(() -> getSSLContext(), keystoreCa()); + } + + static SSLContext verifiedSslContext(CallableSupplier sslContextSupplier) throws Exception { + return verifiedSslContext(sslContextSupplier, keystoreCa()); + } + + static SSLContext verifiedSslContext(CallableSupplier sslContextSupplier, String keystorePath) throws Exception { + // for local testing, run ./mvnw test-compile -Dtest-tls-certs.dir=/tmp/tls-gen/basic + // (generates the Java keystores) + assertNotNull(keystorePath); + String keystorePasswd = keystorePassword(); + assertNotNull(keystorePasswd); + char [] keystorePassword = keystorePasswd.toCharArray(); + + KeyStore tks = KeyStore.getInstance("JKS"); + tks.load(new FileInputStream(keystorePath), keystorePassword); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(tks); + + String p12Path = clientCertPath(); + assertNotNull(p12Path); + String p12Passwd = clientCertPassword(); + assertNotNull(p12Passwd); + KeyStore ks = KeyStore.getInstance("PKCS12"); + char [] p12Password = p12Passwd.toCharArray(); + ks.load(new FileInputStream(p12Path), p12Password); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(ks, p12Password); + + SSLContext c = sslContextSupplier.get(); + c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + return c; + } + + static String keystoreCa() { + return System.getProperty("test-keystore.ca", "./target/ca.keystore"); + } + + static String emptyKeystoreCa() { + return System.getProperty("test-keystore.empty", "./target/empty.keystore"); + } + + static String keystorePassword() { + return System.getProperty("test-keystore.password", "bunnies"); + } + + static String clientCertPath() { + return System.getProperty("test-client-cert.path", "/tmp/tls-gen/basic/client/keycert.p12"); + } + + static String clientCertPassword() { + return System.getProperty("test-client-cert.password", ""); + } + + public static SSLContext getSSLContext() throws NoSuchAlgorithmException { + SSLContext c; + + // pick the first protocol available, preferring TLSv1.2, then TLSv1, + // falling back to SSLv3 if running on an ancient/crippled JDK + for (String proto : Arrays.asList("TLSv1.3", "TLSv1.2", "TLSv1", "SSLv3")) { + try { + c = SSLContext.getInstance(proto); + return c; + } catch (NoSuchAlgorithmException x) { + // keep trying + } + } + throw new NoSuchAlgorithmException(); + } + + static Collection availableTlsProtocols() { + try { + String[] protocols = SSLContext.getDefault().getSupportedSSLParameters().getProtocols(); + return Arrays.stream(protocols).filter(p -> p.toLowerCase().startsWith("tls")).collect( + Collectors.toList()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + } + + @FunctionalInterface + interface CallableSupplier { + + T get() throws Exception; + } +} diff --git a/src/test/java/com/rabbitmq/client/test/ssl/UnverifiedConnection.java b/src/test/java/com/rabbitmq/client/test/ssl/UnverifiedConnection.java index a14a257c24..5a0af90463 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/UnverifiedConnection.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/UnverifiedConnection.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -17,15 +17,13 @@ import com.rabbitmq.client.GetResponse; import com.rabbitmq.client.test.BrokerTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.io.IOException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Test for bug 19356 - SSL Support in rabbitmq @@ -37,10 +35,8 @@ public void openConnection() throws IOException, TimeoutException { try { connectionFactory.useSslProtocol(); - } catch (NoSuchAlgorithmException ex) { - throw new IOException(ex.toString()); - } catch (KeyManagementException ex) { - throw new IOException(ex.toString()); + } catch (Exception ex) { + throw new IOException(ex); } int attempt = 0; diff --git a/src/test/java/com/rabbitmq/client/test/ssl/VerifiedConnection.java b/src/test/java/com/rabbitmq/client/test/ssl/VerifiedConnection.java index 50d4d9003b..e53a83b2f0 100644 --- a/src/test/java/com/rabbitmq/client/test/ssl/VerifiedConnection.java +++ b/src/test/java/com/rabbitmq/client/test/ssl/VerifiedConnection.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,74 +15,47 @@ package com.rabbitmq.client.test.ssl; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -import java.io.FileInputStream; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.impl.nio.NioParams; import java.io.IOException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; +import java.util.Collection; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import javax.net.ssl.KeyManagerFactory; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.SSLSocket; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.test.TestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; import org.slf4j.LoggerFactory; /** * Test for bug 19356 - SSL Support in rabbitmq * */ +@EnabledForJreRange(min = JRE.JAVA_11) public class VerifiedConnection extends UnverifiedConnection { public void openConnection() throws IOException, TimeoutException { try { - String keystorePath = System.getProperty("test-keystore.ca"); - assertNotNull(keystorePath); - String keystorePasswd = System.getProperty("test-keystore.password"); - assertNotNull(keystorePasswd); - char [] keystorePassword = keystorePasswd.toCharArray(); - - KeyStore tks = KeyStore.getInstance("JKS"); - tks.load(new FileInputStream(keystorePath), keystorePassword); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(tks); - - String p12Path = System.getProperty("test-client-cert.path"); - assertNotNull(p12Path); - String p12Passwd = System.getProperty("test-client-cert.password"); - assertNotNull(p12Passwd); - KeyStore ks = KeyStore.getInstance("PKCS12"); - char [] p12Password = p12Passwd.toCharArray(); - ks.load(new FileInputStream(p12Path), p12Password); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(ks, p12Password); - - SSLContext c = getSSLContext(); - c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - + SSLContext c = TlsTestUtils.verifiedSslContext(); connectionFactory = TestUtils.connectionFactory(); connectionFactory.useSslProtocol(c); - } catch (NoSuchAlgorithmException ex) { - throw new IOException(ex.toString()); - } catch (KeyManagementException ex) { - throw new IOException(ex.toString()); - } catch (KeyStoreException ex) { - throw new IOException(ex.toString()); - } catch (CertificateException ex) { - throw new IOException(ex.toString()); - } catch (UnrecoverableKeyException ex) { - throw new IOException(ex.toString()); + } catch (Exception ex) { + throw new IOException(ex); } int attempt = 0; @@ -99,4 +72,40 @@ public void openConnection() fail("Couldn't open TLS connection after 3 attempts"); } } + + @Test + public void connectionGetConsumeProtocols() throws Exception { + Collection availableProtocols = TlsTestUtils.availableTlsProtocols(); + Collection protocols = Stream.of("TLSv1.2", "TLSv1.3") + .filter(p -> availableProtocols.contains(p)) + .collect(Collectors.toList()); + for (String protocol : protocols) { + SSLContext sslContext = SSLContext.getInstance(protocol); + ConnectionFactory cf = TestUtils.connectionFactory(); + cf.useSslProtocol(TlsTestUtils.verifiedSslContext(() -> sslContext)); + AtomicReference> protocolsSupplier = new AtomicReference<>(); + if (TestUtils.USE_NIO) { + cf.useNio(); + NioParams nioParams = new NioParams(); + nioParams.setSslEngineConfigurator( + sslEngine -> protocolsSupplier.set(() -> sslEngine.getEnabledProtocols()) + ); + cf.setNioParams(nioParams); + } else { + cf.setSocketConfigurator(socket -> { + SSLSocket s = (SSLSocket) socket; + protocolsSupplier.set(() -> s.getEnabledProtocols()); + }); + } + try (Connection c = cf.newConnection()) { + CountDownLatch latch = new CountDownLatch(1); + TestUtils.basicGetBasicConsume(c, VerifiedConnection.class.getName(), latch, 100); + boolean messagesReceived = latch.await(5, TimeUnit.SECONDS); + assertTrue(messagesReceived, "Message has not been received"); + assertThat(protocolsSupplier.get()).isNotNull(); + assertThat(protocolsSupplier.get().get()).contains(protocol); + } + } + } + } diff --git a/src/test/java/com/rabbitmq/tools/Host.java b/src/test/java/com/rabbitmq/tools/Host.java index e81aef9a93..8e950cb27e 100644 --- a/src/test/java/com/rabbitmq/tools/Host.java +++ b/src/test/java/com/rabbitmq/tools/Host.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -28,12 +28,17 @@ import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.impl.NetworkConnection; import com.rabbitmq.client.test.TestUtils; +import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class Host { + private static final Logger LOGGER = LoggerFactory.getLogger(Host.class); + private static final String DOCKER_PREFIX = "DOCKER:"; private static final Pattern CONNECTION_NAME_PATTERN = Pattern.compile("\"connection_name\",\"(?[a-zA-Z0-9\\-]+)?\""); @@ -49,25 +54,68 @@ public static String capture(InputStream is) return buff.toString(); } - public static Process executeCommand(String command) throws IOException + public static ProcessState executeCommand(String command) throws IOException { Process pr = executeCommandProcess(command); + InputStreamPumpState inputState = new InputStreamPumpState(pr.getInputStream()); + InputStreamPumpState errorState = new InputStreamPumpState(pr.getErrorStream()); - int ev = waitForExitValue(pr); + int ev = waitForExitValue(pr, inputState, errorState); + inputState.pump(); + errorState.pump(); if (ev != 0) { - String stdout = capture(pr.getInputStream()); - String stderr = capture(pr.getErrorStream()); throw new IOException("unexpected command exit value: " + ev + "\ncommand: " + command + "\n" + - "\nstdout:\n" + stdout + - "\nstderr:\n" + stderr + "\n"); + "\nstdout:\n" + inputState.buffer.toString() + + "\nstderr:\n" + errorState.buffer.toString() + "\n"); } - return pr; + return new ProcessState(pr, inputState, errorState); } - private static int waitForExitValue(Process pr) { + static class ProcessState { + + private final Process process; + private final InputStreamPumpState inputState; + private final InputStreamPumpState errorState; + + ProcessState(Process process, InputStreamPumpState inputState, + InputStreamPumpState errorState) { + this.process = process; + this.inputState = inputState; + this.errorState = errorState; + } + + private String output() { + return inputState.buffer.toString(); + } + + } + + private static class InputStreamPumpState { + + private final BufferedReader reader; + private final StringBuilder buffer; + + private InputStreamPumpState(InputStream in) { + this.reader = new BufferedReader(new InputStreamReader(in)); + this.buffer = new StringBuilder(); + } + + void pump() throws IOException { + String line; + while ((line = reader.readLine()) != null) { + buffer.append(line).append("\n"); + } + } + + } + + private static int waitForExitValue(Process pr, InputStreamPumpState inputState, + InputStreamPumpState errorState) throws IOException { while(true) { try { + inputState.pump(); + errorState.pump(); pr.waitFor(); break; } catch (InterruptedException ignored) {} @@ -78,7 +126,18 @@ private static int waitForExitValue(Process pr) { public static Process executeCommandIgnoringErrors(String command) throws IOException { Process pr = executeCommandProcess(command); - waitForExitValue(pr); + InputStreamPumpState inputState = new InputStreamPumpState(pr.getInputStream()); + InputStreamPumpState errorState = new InputStreamPumpState(pr.getErrorStream()); + inputState.pump(); + errorState.pump(); + boolean exited = false; + try { + exited = pr.waitFor(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + } + if (!exited) { + LOGGER.warn("Command '{}' did not finish in 30 seconds", command); + } return pr; } @@ -101,12 +160,12 @@ private static Process executeCommandProcess(String command) throws IOException } public static boolean isRabbitMqCtlCommandAvailable(String command) throws IOException { - Process process = rabbitmqctlIgnoreErrors(""); - String stderr = capture(process.getErrorStream()); - return stderr.contains(command); + Process process = rabbitmqctlIgnoreErrors(command + " --help"); + int exitValue = process.exitValue(); + return exitValue == 0; } - public static Process rabbitmqctl(String command) throws IOException { + public static ProcessState rabbitmqctl(String command) throws IOException { return executeCommand(rabbitmqctlCommand() + rabbitmqctlNodenameArgument() + " " + command); @@ -130,7 +189,7 @@ public static void clearResourceAlarm(String source) throws IOException { rabbitmqctl("eval 'rabbit_alarm:clear_alarm({resource_limit, " + source + ", node()}).'"); } - public static Process invokeMakeTarget(String command) throws IOException { + public static ProcessState invokeMakeTarget(String command) throws IOException { File rabbitmqctl = new File(rabbitmqctlCommand()); return executeCommand(makeCommand() + " -C \'" + rabbitmqDir() + "\'" + @@ -295,7 +354,7 @@ public String toString() { } public static List listConnections() throws IOException { - String output = capture(rabbitmqctl("list_connections -q pid peer_port client_properties").getInputStream()); + String output = rabbitmqctl("list_connections -q pid peer_port client_properties").output(); // output (header line presence depends on broker version): // pid peer_port // 58713 diff --git a/src/test/java/com/rabbitmq/utility/IntAllocatorTests.java b/src/test/java/com/rabbitmq/utility/IntAllocatorTests.java index d29e134442..5e468a60e3 100644 --- a/src/test/java/com/rabbitmq/utility/IntAllocatorTests.java +++ b/src/test/java/com/rabbitmq/utility/IntAllocatorTests.java @@ -1,4 +1,4 @@ -// Copyright (c) 2007-2020 VMware, Inc. or its affiliates. All rights reserved. +// Copyright (c) 2007-2023 VMware, Inc. or its affiliates. All rights reserved. // // This software, the RabbitMQ Java client library, is triple-licensed under the // Mozilla Public License 2.0 ("MPL"), the GNU General Public License version 2 @@ -15,14 +15,14 @@ package com.rabbitmq.utility; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class IntAllocatorTests { @@ -41,38 +41,38 @@ public class IntAllocatorTests { iAll.free(trial); set.remove(trial); } else { - assertTrue("Did not reserve free integer " + trial, iAll.reserve(trial)); + assertTrue(iAll.reserve(trial), "Did not reserve free integer " + trial); set.add(trial); } } for (int trial : set) { - assertFalse("Integer " + trial + " not allocated!", iAll.reserve(trial)); + assertFalse(iAll.reserve(trial), "Integer " + trial + " not allocated!"); } } - @Test public void allocateAndFree() throws Exception { + @Test public void allocateAndFree() { Set set = new HashSet(); for (int i=0; i < TEST_ITERATIONS; ++i) { if (getBool(rand)) { int trial = iAll.allocate(); - assertFalse("Already allocated " + trial, set.contains(trial)); + assertFalse(set.contains(trial), "Already allocated " + trial); set.add(trial); } else { if (!set.isEmpty()) { int trial = extractOne(set); - assertFalse("Allocator agreed to reserve " + trial, iAll.reserve(trial)); + assertFalse(iAll.reserve(trial), "Allocator agreed to reserve " + trial); iAll.free(trial); } } } for (int trial : set) { - assertFalse("Integer " + trial + " should be allocated!", iAll.reserve(trial)); + assertFalse(iAll.reserve(trial), "Integer " + trial + " should be allocated!"); } } - @Test public void testToString() throws Exception { + @Test public void testToString() { IntAllocator ibs = new IntAllocator(LO_RANGE, HI_RANGE); assertEquals("IntAllocator{allocated = []}", ibs.toString()); ibs.allocate(); diff --git a/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension new file mode 100644 index 0000000000..5d5a5c135a --- /dev/null +++ b/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension @@ -0,0 +1 @@ +com.rabbitmq.client.AmqpClientTestExtension \ No newline at end of file diff --git a/src/test/resources/junit-platform.properties b/src/test/resources/junit-platform.properties new file mode 100644 index 0000000000..b059a65dc4 --- /dev/null +++ b/src/test/resources/junit-platform.properties @@ -0,0 +1 @@ +junit.jupiter.extensions.autodetection.enabled=true \ No newline at end of file diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index 4bd2e37606..f47371567e 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -5,7 +5,11 @@ - + + + + + \ No newline at end of file