From 2cf97a0e677fbc995466f8b318010bdc0fd493b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20L=C3=B3pez=20Le=C3=B3n?= Date: Wed, 11 May 2022 19:08:31 -0300 Subject: [PATCH] Replace expected Junit 4 @Test field with assertThatThrownBy (#3814) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix two operand stack tests Signed-off-by: Diego López León * Remove unreachable assert Signed-off-by: Diego López León * Replace expected annotation field with assert Signed-off-by: Diego López León * Extract variables to let only a single call for assert Signed-off-by: Diego López León Co-authored-by: Sally MacFarlane --- ...vateContractPublicStateAcceptanceTest.java | 8 ++-- .../privacy/contracts/PrivacyGroupTest.java | 17 ++++--- .../cli/operator/OperatorSubCommandTest.java | 19 ++++---- .../stable/LoggingLevelOptionTest.java | 6 ++- .../ibftlegacy/BftExtraDataCodecTest.java | 11 +++-- .../crypto/Blake2bfMessageDigestTest.java | 32 ++++++++----- .../hyperledger/besu/crypto/KeyPairTest.java | 12 +++-- .../besu/crypto/KeyPairUtilTest.java | 8 ++-- .../besu/crypto/SECP256K1Test.java | 11 +++-- .../besu/crypto/SECP256R1Test.java | 11 +++-- .../besu/crypto/SECPPrivateKeyTest.java | 6 ++- .../besu/crypto/SECPPublicKeyTest.java | 18 ++++--- .../besu/crypto/SECPSignatureTest.java | 11 +++-- .../crypto/SignatureAlgorithmFactoryTest.java | 7 ++- .../api/jsonrpc/JsonResponseStreamerTest.java | 6 ++- .../authentication/EngineAuthServiceTest.java | 16 ++++--- .../methods/AdminLogsRemoveCacheTest.java | 6 ++- .../methods/AdminLogsRepairCacheTest.java | 6 ++- .../websocket/JsonResponseStreamerTest.java | 5 +- .../ethereum/chain/DefaultBlockchainTest.java | 15 +++--- ...lexiblePrivacyPrecompiledContractTest.java | 5 +- .../PrivacyPrecompiledContractTest.java | 5 +- ...tiTenancyPrivacyControllerOnchainTest.java | 15 +++--- .../MultiTenancyPrivacyControllerTest.java | 9 ++-- .../privacy/PrivateTransactionTest.java | 45 +++++++++-------- .../besu/ethereum/vm/AddressTest.java | 16 ++++--- .../besu/ethereum/vm/OperandStackTest.java | 32 +++++++------ .../eth/manager/EthProtocolManagerTest.java | 12 +++-- .../fastsync/FastDownloaderFactoryTest.java | 28 ++++++----- .../PeerDiscoveryPacketSedesTest.java | 13 +++-- .../p2p/discovery/internal/PacketTest.java | 6 ++- ...overyControllerDistanceCalculatorTest.java | 5 +- .../internal/PeerDiscoveryControllerTest.java | 5 +- .../NetworkingServiceLifecycleTest.java | 48 ++++++++++++------- .../ethereum/rlp/BytesValueRLPOutputTest.java | 13 ++--- .../besu/ethereum/rlp/InvalidRLPRefTest.java | 7 ++- .../trie/AbstractMerklePatriciaTrieTest.java | 6 ++- .../KubernetesUnknownNatManagerTest.java | 6 ++- .../HardwareKeyStoreFileWrapperTest.java | 23 +++++---- 39 files changed, 331 insertions(+), 199 deletions(-) diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/PrivateContractPublicStateAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/PrivateContractPublicStateAcceptanceTest.java index 07d95bc371..a65ba9df7d 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/PrivateContractPublicStateAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/PrivateContractPublicStateAcceptanceTest.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.tests.acceptance.privacy; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.web3j.utils.Restriction.UNRESTRICTED; import org.hyperledger.besu.tests.acceptance.dsl.privacy.ParameterizedEnclaveTestBase; @@ -93,7 +94,7 @@ public class PrivateContractPublicStateAcceptanceTest extends ParameterizedEncla assertThat(result).isEqualTo(BigInteger.valueOf(12)); } - @Test(expected = ContractCallException.class) + @Test public void mustNotAllowAccessToPrivateStateFromPublicTx() throws Exception { final EventEmitter privateEventEmitter = transactionNode.execute( @@ -108,8 +109,9 @@ public class PrivateContractPublicStateAcceptanceTest extends ParameterizedEncla final CrossContractReader publicReader = transactionNode.execute( contractTransactions.createSmartContract(CrossContractReader.class)); - - publicReader.read(privateEventEmitter.getContractAddress()).send(); + final RemoteFunctionCall functionCall = + publicReader.read(privateEventEmitter.getContractAddress()); + assertThatThrownBy(functionCall::send).isInstanceOf(ContractCallException.class); } @Test diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/contracts/PrivacyGroupTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/contracts/PrivacyGroupTest.java index 4b2de711eb..3cf9a943a4 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/contracts/PrivacyGroupTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/contracts/PrivacyGroupTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.tests.acceptance.privacy.contracts; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.privacy.contracts.generated.DefaultFlexiblePrivacyGroupManagementContract; import org.hyperledger.besu.tests.acceptance.dsl.AcceptanceTestBase; @@ -126,15 +127,18 @@ public class PrivacyGroupTest extends AcceptanceTestBase { assertThat(firstParticipant.raw()).isEqualTo(participantsAfterRemove.get(0)); } - @Test(expected = TransactionException.class) + @Test public void cannotAddToContractWhenNotLocked() throws Exception { defaultPrivacyGroupManagementContract .addParticipants(Collections.singletonList(thirdParticipant.raw())) .send(); - defaultPrivacyGroupManagementContract - .addParticipants(Collections.singletonList(secondParticipant.raw())) - .send(); + assertThatThrownBy( + () -> + defaultPrivacyGroupManagementContract + .addParticipants(Collections.singletonList(secondParticipant.raw())) + .send()) + .isInstanceOf(TransactionException.class); } @Test @@ -179,12 +183,13 @@ public class PrivacyGroupTest extends AcceptanceTestBase { assertThat(secondParticipant.raw()).isEqualTo(participants.get(2)); } - @Test(expected = TransactionException.class) + @Test public void cannotLockTwice() throws Exception { defaultPrivacyGroupManagementContract .addParticipants(Collections.singletonList(thirdParticipant.raw())) .send(); defaultPrivacyGroupManagementContract.lock().send(); - defaultPrivacyGroupManagementContract.lock().send(); + assertThatThrownBy(() -> defaultPrivacyGroupManagementContract.lock().send()) + .isInstanceOf(TransactionException.class); } } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/operator/OperatorSubCommandTest.java b/besu/src/test/java/org/hyperledger/besu/cli/operator/OperatorSubCommandTest.java index ccb115f5d8..a79724b389 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/operator/OperatorSubCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/operator/OperatorSubCommandTest.java @@ -238,15 +238,18 @@ public class OperatorSubCommandTest extends CommandTestAbstract { .isInstanceOf(CommandLine.ExecutionException.class); } - @Test(expected = CommandLine.ExecutionException.class) + @Test public void shouldFailIfOutputDirectoryNonEmpty() throws IOException { - runCmdAndCheckOutput( - cmd(), - "/operator/config_generate_keys.json", - FileSystems.getDefault().getPath("."), - "genesis.json", - true, - asList("key.pub", "key.priv")); + assertThatThrownBy( + () -> + runCmdAndCheckOutput( + cmd(), + "/operator/config_generate_keys.json", + FileSystems.getDefault().getPath("."), + "genesis.json", + true, + asList("key.pub", "key.priv"))) + .isInstanceOf(CommandLine.ExecutionException.class); } @Test diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOptionTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOptionTest.java index 78b2d4d55b..f63136b2cb 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOptionTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOptionTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.cli.options.stable; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Answers.RETURNS_DEEP_STUBS; import java.util.Arrays; @@ -52,9 +53,10 @@ public class LoggingLevelOptionTest { }); } - @Test(expected = ParameterException.class) + @Test public void failsOnUnknownLevel() { levelOption.spec = Mockito.mock(CommandSpec.class, RETURNS_DEEP_STUBS); - levelOption.setLogLevel("unknown"); + assertThatThrownBy(() -> levelOption.setLogLevel("unknown")) + .isInstanceOf(ParameterException.class); } } diff --git a/consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/BftExtraDataCodecTest.java b/consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/BftExtraDataCodecTest.java index 54501c2888..6e4fcce930 100644 --- a/consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/BftExtraDataCodecTest.java +++ b/consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/BftExtraDataCodecTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.consensus.ibftlegacy; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.crypto.SECPSignature; import org.hyperledger.besu.crypto.SignatureAlgorithm; @@ -98,7 +99,7 @@ public class BftExtraDataCodecTest { assertThat(extraData.getValidators()).isEqualTo(validators); } - @Test(expected = RLPException.class) + @Test public void incorrectlyStructuredRlpThrowsException() { final SECPSignature proposerSeal = SIGNATURE_ALGORITHM.get().createSignature(BigInteger.ONE, BigInteger.ONE, (byte) 0); @@ -115,10 +116,11 @@ public class BftExtraDataCodecTest { final Bytes bufferToInject = Bytes.wrap(Bytes.wrap(new byte[32]), encoder.encoded()); - IbftExtraData.decodeRaw(bufferToInject); + assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject)) + .isInstanceOf(RLPException.class); } - @Test(expected = RLPException.class) + @Test public void incorrectlySizedVanityDataThrowsException() { final List
validators = Arrays.asList(Address.ECREC, Address.SHA256); final SECPSignature proposerSeal = @@ -137,7 +139,8 @@ public class BftExtraDataCodecTest { final Bytes bufferToInject = Bytes.wrap(Bytes.wrap(new byte[31]), encoder.encoded()); - IbftExtraData.decodeRaw(bufferToInject); + assertThatThrownBy(() -> IbftExtraData.decodeRaw(bufferToInject)) + .isInstanceOf(RLPException.class); } @Test diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/Blake2bfMessageDigestTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/Blake2bfMessageDigestTest.java index 0cb9152779..deb4de81f3 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/Blake2bfMessageDigestTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/Blake2bfMessageDigestTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.crypto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.bouncycastle.util.Pack; import org.junit.Before; @@ -84,31 +85,40 @@ public class Blake2bfMessageDigestTest { assertThat(messageDigest.digest()).isEqualTo(BLAKE2F_ALL_ZERO_NEGATIVE_ROUNDS); } - @Test(expected = IllegalStateException.class) + @Test public void throwsIfBufferUpdatedWithLessThat213Bytes() { for (int i = 0; i < 212; i++) { messageDigest.update((byte) 0); } - messageDigest.digest(); + assertThatThrownBy(() -> messageDigest.digest()).isInstanceOf(IllegalStateException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void throwsIfBufferUpdatedWithMoreThat213Bytes() { - for (int i = 0; i < 214; i++) { - messageDigest.update((byte) 0); - } + assertThatThrownBy( + () -> { + for (int i = 0; i < 214; i++) { + messageDigest.update((byte) 0); + } + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void throwsIfBufferUpdatedLargeByteArray() { final byte[] update = new byte[213]; messageDigest.update((byte) 0); - messageDigest.update(update, 0, 213); + assertThatThrownBy(() -> messageDigest.update(update, 0, 213)) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void throwsIfEmptyBufferUpdatedLargeByteArray() { - final byte[] update = new byte[214]; - messageDigest.update(update, 0, 214); + assertThatThrownBy( + () -> { + final byte[] update = new byte[214]; + messageDigest.update(update, 0, 214); + }) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairTest.java index e6b3103d16..a8c1ac7e8f 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairTest.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.crypto; import static org.apache.tuweni.bytes.Bytes.fromHexString; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigInteger; import java.security.KeyPairGenerator; @@ -52,14 +53,17 @@ public class KeyPairTest { curve = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH()); } - @Test(expected = NullPointerException.class) + @Test public void createKeyPair_PublicKeyNull() { - new KeyPair(null, SECPPublicKey.create(Bytes.wrap(new byte[64]), ALGORITHM)); + final SECPPublicKey publicKey = SECPPublicKey.create(Bytes.wrap(new byte[64]), ALGORITHM); + assertThatThrownBy(() -> new KeyPair(null, publicKey)).isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void createKeyPair_PrivateKeyNull() { - new KeyPair(SECPPrivateKey.create(Bytes32.wrap(new byte[32]), ALGORITHM), null); + final SECPPrivateKey privateKey = SECPPrivateKey.create(Bytes32.wrap(new byte[32]), ALGORITHM); + assertThatThrownBy(() -> new KeyPair(privateKey, null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairUtilTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairUtilTest.java index 687ff1829c..13c78d52bd 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairUtilTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairUtilTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.crypto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; @@ -30,9 +31,10 @@ public class KeyPairUtilTest { .isNotNull(); } - @Test(expected = IllegalArgumentException.class) + @Test public void shouldNotLoadInvalidKeyPair() throws Exception { - KeyPairUtil.loadKeyPair( - new File(this.getClass().getResource("/invalidPrivateKey.txt").toURI())); + final File keyFile = new File(this.getClass().getResource("/invalidPrivateKey.txt").toURI()); + assertThatThrownBy(() -> KeyPairUtil.loadKeyPair(keyFile)) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256K1Test.java b/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256K1Test.java index 87690321ac..060bdad844 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256K1Test.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256K1Test.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.crypto; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.crypto.Hash.keccak256; import java.io.File; @@ -115,19 +116,21 @@ public class SECP256K1Test { assertThat(secp256K1.verify(data, signature, keyPair.getPublicKey(), Hash::keccak256)).isTrue(); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidFileThrowsInvalidKeyPairException() throws Exception { final File tempFile = Files.createTempFile(suiteName(), ".keypair").toFile(); tempFile.deleteOnExit(); Files.write(tempFile.toPath(), "not valid".getBytes(UTF_8)); - KeyPairUtil.load(tempFile); + assertThatThrownBy(() -> KeyPairUtil.load(tempFile)) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidMultiLineFileThrowsInvalidIdException() throws Exception { final File tempFile = Files.createTempFile(suiteName(), ".keypair").toFile(); tempFile.deleteOnExit(); Files.write(tempFile.toPath(), "not\n\nvalid".getBytes(UTF_8)); - KeyPairUtil.load(tempFile); + assertThatThrownBy(() -> KeyPairUtil.load(tempFile)) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256R1Test.java b/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256R1Test.java index 6de42dcbd5..bd791ef9be 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256R1Test.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/SECP256R1Test.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.crypto; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.crypto.Hash.keccak256; import java.io.File; @@ -163,20 +164,22 @@ public class SECP256R1Test { }); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidFileThrowsInvalidKeyPairException() throws Exception { final File tempFile = Files.createTempFile(suiteName(), ".keypair").toFile(); tempFile.deleteOnExit(); Files.write(tempFile.toPath(), "not valid".getBytes(UTF_8)); - KeyPairUtil.load(tempFile); + assertThatThrownBy(() -> KeyPairUtil.load(tempFile)) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidMultiLineFileThrowsInvalidIdException() throws Exception { final File tempFile = Files.createTempFile(suiteName(), ".keypair").toFile(); tempFile.deleteOnExit(); Files.write(tempFile.toPath(), "not\n\nvalid".getBytes(UTF_8)); - KeyPairUtil.load(tempFile); + assertThatThrownBy(() -> KeyPairUtil.load(tempFile)) + .isInstanceOf(IllegalArgumentException.class); } private static class SignTestVector { diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPrivateKeyTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPrivateKeyTest.java index d5d64df939..d99d494091 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPrivateKeyTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPrivateKeyTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.crypto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; import java.math.BigInteger; @@ -54,9 +55,10 @@ public class SECPPrivateKeyTest { suiteName = clazz.getSimpleName() + "-" + suiteStartTime; } - @Test(expected = NullPointerException.class) + @Test public void createPrivateKey_NullEncoding() { - SECPPrivateKey.create((Bytes32) null, ALGORITHM); + assertThatThrownBy(() -> SECPPrivateKey.create((Bytes32) null, ALGORITHM)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPublicKeyTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPublicKeyTest.java index e29097e88b..e5e9e6bb3a 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPublicKeyTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/SECPPublicKeyTest.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.crypto; import static org.apache.tuweni.bytes.Bytes.fromHexString; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigInteger; @@ -38,19 +39,24 @@ public class SECPPublicKeyTest { curve = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH()); } - @Test(expected = NullPointerException.class) + @Test public void createPublicKey_NullEncoding() { - SECPPublicKey.create((Bytes) null, ALGORITHM); + assertThatThrownBy(() -> SECPPublicKey.create((Bytes) null, ALGORITHM)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void createPublicKey_EncodingTooShort() { - SECPPublicKey.create(Bytes.wrap(new byte[63]), ALGORITHM); + final Bytes publicKey = Bytes.wrap(new byte[63]); + assertThatThrownBy(() -> SECPPublicKey.create(publicKey, ALGORITHM)) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void createPublicKey_EncodingTooLong() { - SECPPublicKey.create(Bytes.wrap(new byte[65]), ALGORITHM); + final Bytes publicKey = Bytes.wrap(new byte[65]); + assertThatThrownBy(() -> SECPPublicKey.create(publicKey, ALGORITHM)) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/SECPSignatureTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/SECPSignatureTest.java index 88de758ec4..a737a93f0b 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/SECPSignatureTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/SECPSignatureTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.crypto; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigInteger; @@ -46,13 +47,15 @@ public class SECPSignatureTest { assertThat(signature.getRecId()).isEqualTo((byte) 0); } - @Test(expected = NullPointerException.class) + @Test public void createSignature_NoR() { - SECPSignature.create(null, BigInteger.ZERO, (byte) 27, curveOrder); + assertThatThrownBy(() -> SECPSignature.create(null, BigInteger.ZERO, (byte) 27, curveOrder)) + .isInstanceOf(NullPointerException.class); } - @Test(expected = NullPointerException.class) + @Test public void createSignature_NoS() { - SECPSignature.create(BigInteger.ZERO, null, (byte) 27, curveOrder); + assertThatThrownBy(() -> SECPSignature.create(BigInteger.ZERO, null, (byte) 27, curveOrder)) + .isInstanceOf(NullPointerException.class); } } diff --git a/crypto/src/test/java/org/hyperledger/besu/crypto/SignatureAlgorithmFactoryTest.java b/crypto/src/test/java/org/hyperledger/besu/crypto/SignatureAlgorithmFactoryTest.java index be13269011..38c71c99db 100644 --- a/crypto/src/test/java/org/hyperledger/besu/crypto/SignatureAlgorithmFactoryTest.java +++ b/crypto/src/test/java/org/hyperledger/besu/crypto/SignatureAlgorithmFactoryTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.crypto; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import org.junit.Before; import org.junit.Test; @@ -42,11 +43,13 @@ public class SignatureAlgorithmFactoryTest { .isEqualTo(SECP256K1.class.getSimpleName()); } - @Test(expected = RuntimeException.class) + @Test public void shouldThrowExceptionWhenSetMoreThanOnce() { SignatureAlgorithmFactory.setInstance(SignatureAlgorithmType.create("secp256k1")); assertThat(SignatureAlgorithmFactory.isInstanceSet()).isTrue(); - SignatureAlgorithmFactory.setInstance(SignatureAlgorithmType.create("secp256k1")); + assertThatThrownBy( + () -> SignatureAlgorithmFactory.setInstance(SignatureAlgorithmType.create("secp256k1"))) + .isInstanceOf(RuntimeException.class); } } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonResponseStreamerTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonResponseStreamerTest.java index f8116238c7..3e3f8efc15 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonResponseStreamerTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonResponseStreamerTest.java @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.ethereum.api.jsonrpc; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.never; @@ -94,11 +95,12 @@ public class JsonResponseStreamerTest { verify(httpResponse).end(); } - @Test(expected = IOException.class) + @Test public void stopOnError() throws IOException { try (JsonResponseStreamer streamer = new JsonResponseStreamer(failedResponse, testAddress)) { streamer.write("xyz".getBytes(StandardCharsets.UTF_8)); - streamer.write("abc".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> streamer.write("abc".getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IOException.class); } verify(failedResponse).write(argThat(bufferContains("xyz"))); diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/authentication/EngineAuthServiceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/authentication/EngineAuthServiceTest.java index 4da8c24293..9cf3e00c89 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/authentication/EngineAuthServiceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/authentication/EngineAuthServiceTest.java @@ -17,8 +17,10 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.authentication; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; @@ -76,24 +78,26 @@ public class EngineAuthServiceTest { auth.authenticate(token, authHandler); } - @Test(expected = UnsecurableEngineApiException.class) + @Test public void throwsOnShortKey() throws IOException, URISyntaxException { Vertx vertx = mock(Vertx.class); final Path userKey = Paths.get( ClassLoader.getSystemResource("authentication/ee-jwt-secret-too-short.hex").toURI()); Path dataDir = Files.createTempDirectory("besuUnitTest"); - EngineAuthService auth = new EngineAuthService(vertx, Optional.of(userKey.toFile()), dataDir); - assertThat(auth).isNotNull(); + final Optional signingKey = Optional.of(userKey.toFile()); + assertThatThrownBy(() -> new EngineAuthService(vertx, signingKey, dataDir)) + .isInstanceOf(UnsecurableEngineApiException.class); } - @Test(expected = UnsecurableEngineApiException.class) + @Test public void throwsKeyFileMissing() throws IOException, URISyntaxException { Vertx vertx = mock(Vertx.class); final Path userKey = Paths.get("no-such-file.hex"); Path dataDir = Files.createTempDirectory("besuUnitTest"); - EngineAuthService auth = new EngineAuthService(vertx, Optional.of(userKey.toFile()), dataDir); - assertThat(auth).isNotNull(); + final Optional signingKey = Optional.of(userKey.toFile()); + assertThatThrownBy(() -> new EngineAuthService(vertx, signingKey, dataDir)) + .isInstanceOf(UnsecurableEngineApiException.class); } @Test diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCacheTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCacheTest.java index 24400bef82..0bb1f7b4da 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCacheTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCacheTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.when; @@ -155,7 +156,7 @@ public class AdminLogsRemoveCacheTest { assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); } - @Test(expected = IllegalStateException.class) + @Test public void requestBlockNumberNotFoundTest() { final JsonRpcRequestContext request = new JsonRpcRequestContext( @@ -164,7 +165,8 @@ public class AdminLogsRemoveCacheTest { when(blockchainQueries.getBlockchain()).thenReturn(blockchain); when(blockchain.getBlockByNumber(anyLong())).thenReturn(Optional.empty()); - adminLogsRemoveCache.response(request); + assertThatThrownBy(() -> adminLogsRemoveCache.response(request)) + .isInstanceOf(IllegalStateException.class); } @Test diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCacheTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCacheTest.java index a0d2684385..226eafb17b 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCacheTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCacheTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; @@ -91,7 +92,7 @@ public class AdminLogsRepairCacheTest { assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); } - @Test(expected = IllegalStateException.class) + @Test public void requestBlockNumberNotFoundTest() { final JsonRpcRequestContext request = new JsonRpcRequestContext( @@ -100,6 +101,7 @@ public class AdminLogsRepairCacheTest { when(blockchainQueries.getBlockchain()).thenReturn(blockchain); when(blockchain.getBlockByNumber(anyLong())).thenReturn(Optional.empty()); - adminLogsRepairCache.response(request); + assertThatThrownBy(() -> adminLogsRepairCache.response(request)) + .isInstanceOf(IllegalStateException.class); } } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/JsonResponseStreamerTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/JsonResponseStreamerTest.java index 2c08a5de40..4228e6ed7d 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/JsonResponseStreamerTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/JsonResponseStreamerTest.java @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.ethereum.api.jsonrpc.websocket; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.never; @@ -87,12 +88,12 @@ public class JsonResponseStreamerTest { verify(response).writeFrame(argThat(frameContains("\n", true))); } - @Test(expected = IOException.class) + @Test public void stopOnError() throws IOException { try (JsonResponseStreamer streamer = new JsonResponseStreamer(failedResponse)) { streamer.write("xyz".getBytes(StandardCharsets.UTF_8)); streamer.write('\n'); - streamer.write('\n'); + assertThatThrownBy(() -> streamer.write('\n')).isInstanceOf(IOException.class); } verify(failedResponse).writeFrame(argThat(frameContains("xyz", false))); diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchainTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchainTest.java index 13fc62b934..5fece9c635 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchainTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchainTest.java @@ -213,7 +213,7 @@ public class DefaultBlockchainTest { assertThat(blockchain.getForks()).isEmpty(); } - @Test(expected = IllegalArgumentException.class) + @Test public void appendUnconnectedBlock() { final BlockDataGenerator gen = new BlockDataGenerator(); @@ -225,10 +225,11 @@ public class DefaultBlockchainTest { new BlockDataGenerator.BlockOptions().setBlockNumber(1L).setParentHash(Hash.ZERO); final Block newBlock = gen.block(options); final List receipts = gen.receipts(newBlock); - blockchain.appendBlock(newBlock, receipts); + assertThatThrownBy(() -> blockchain.appendBlock(newBlock, receipts)) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void appendBlockWithMismatchedReceipts() { final BlockDataGenerator gen = new BlockDataGenerator(); @@ -243,7 +244,8 @@ public class DefaultBlockchainTest { final Block newBlock = gen.block(options); final List receipts = gen.receipts(newBlock); receipts.add(gen.receipt()); - blockchain.appendBlock(newBlock, receipts); + assertThatThrownBy(() -> blockchain.appendBlock(newBlock, receipts)) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -801,7 +803,7 @@ public class DefaultBlockchainTest { assertThat(blockchain.observerCount()).isEqualTo(0); } - @Test(expected = NullPointerException.class) + @Test public void blockAddedObserver_nullObserver() { final BlockDataGenerator gen = new BlockDataGenerator(); @@ -809,7 +811,8 @@ public class DefaultBlockchainTest { final Block genesisBlock = gen.genesisBlock(); final DefaultBlockchain blockchain = createMutableBlockchain(kvStore, genesisBlock); - blockchain.observeBlockAdded(null); + assertThatThrownBy(() -> blockchain.observeBlockAdded(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/FlexiblePrivacyPrecompiledContractTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/FlexiblePrivacyPrecompiledContractTest.java index 7a0f30b4a0..248985e833 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/FlexiblePrivacyPrecompiledContractTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/FlexiblePrivacyPrecompiledContractTest.java @@ -257,14 +257,15 @@ public class FlexiblePrivacyPrecompiledContractTest { assertThat(actual).isEqualTo(Bytes.EMPTY); } - @Test(expected = RuntimeException.class) + @Test public void testEnclaveDown() { final Enclave enclave = mock(Enclave.class); final PrivacyPrecompiledContract contract = buildPrivacyPrecompiledContract(enclave); when(enclave.receive(any(String.class))).thenThrow(new RuntimeException()); - contract.computePrecompile(privateTransactionLookupId, messageFrame); + assertThatThrownBy(() -> contract.computePrecompile(privateTransactionLookupId, messageFrame)) + .isInstanceOf(RuntimeException.class); } @Test diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/PrivacyPrecompiledContractTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/PrivacyPrecompiledContractTest.java index 4b7eb9aecc..37655119c4 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/PrivacyPrecompiledContractTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/PrivacyPrecompiledContractTest.java @@ -191,14 +191,15 @@ public class PrivacyPrecompiledContractTest { assertThat(actual).isEqualTo(Bytes.EMPTY); } - @Test(expected = RuntimeException.class) + @Test public void testEnclaveDown() { final Enclave enclave = mock(Enclave.class); final PrivacyPrecompiledContract contract = buildPrivacyPrecompiledContract(enclave); when(enclave.receive(any(String.class))).thenThrow(new RuntimeException()); - contract.computePrecompile(privateTransactionLookupId, messageFrame); + assertThatThrownBy(() -> contract.computePrecompile(privateTransactionLookupId, messageFrame)) + .isInstanceOf(RuntimeException.class); } @Test diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerOnchainTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerOnchainTest.java index d34616b764..012da9c350 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerOnchainTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerOnchainTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.privacy; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -71,7 +72,7 @@ public class MultiTenancyPrivacyControllerOnchainTest { assertThat(result.get().getValidationResult().isValid()).isTrue(); } - @Test(expected = MultiTenancyValidationException.class) + @Test public void simulatePrivateTransactionFailsForAbsentEnclaveKey() { doThrow( new MultiTenancyValidationException( @@ -79,10 +80,12 @@ public class MultiTenancyPrivacyControllerOnchainTest { .when(privacyController) .verifyPrivacyGroupContainsPrivacyUserId( PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY2, Optional.of(1L)); - multiTenancyPrivacyController.simulatePrivateTransaction( - PRIVACY_GROUP_ID, - ENCLAVE_PUBLIC_KEY2, - new CallParameter(Address.ZERO, Address.ZERO, 0, Wei.ZERO, Wei.ZERO, Bytes.EMPTY), - 1); + final CallParameter callParams = + new CallParameter(Address.ZERO, Address.ZERO, 0, Wei.ZERO, Wei.ZERO, Bytes.EMPTY); + assertThatThrownBy( + () -> + multiTenancyPrivacyController.simulatePrivateTransaction( + PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY2, callParams, 1)) + .isInstanceOf(MultiTenancyValidationException.class); } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerTest.java index f710c3b340..3909501556 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerTest.java @@ -323,12 +323,15 @@ public class MultiTenancyPrivacyControllerTest { PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY1); } - @Test(expected = MultiTenancyValidationException.class) + @Test public void verifyPrivacyGroupDoesNotMatchEnclaveKeyThrowsException() { doThrow(MultiTenancyValidationException.class) .when(privacyController) .verifyPrivacyGroupContainsPrivacyUserId(PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY2); - multiTenancyPrivacyController.verifyPrivacyGroupContainsPrivacyUserId( - PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY2); + assertThatThrownBy( + () -> + multiTenancyPrivacyController.verifyPrivacyGroupContainsPrivacyUserId( + PRIVACY_GROUP_ID, ENCLAVE_PUBLIC_KEY2)) + .isInstanceOf(MultiTenancyValidationException.class); } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/PrivateTransactionTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/PrivateTransactionTest.java index 1ba042eea8..78b0dc8e93 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/PrivateTransactionTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/PrivateTransactionTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.privacy; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.plugin.data.Restriction.RESTRICTED; import static org.hyperledger.besu.plugin.data.Restriction.UNRESTRICTED; @@ -309,9 +310,11 @@ public class PrivateTransactionTest { assertThat(p).isEqualTo(VALID_SIGNED_PRIVATE_TRANSACTION); } - @Test(expected = RLPException.class) + @Test public void testReadFromInvalid() { - PrivateTransaction.readFrom(new BytesValueRLPInput(Bytes.fromHexString(INVALID_RLP), false)); + final BytesValueRLPInput input = + new BytesValueRLPInput(Bytes.fromHexString(INVALID_RLP), false); + assertThatThrownBy(() -> PrivateTransaction.readFrom(input)).isInstanceOf(RLPException.class); } @Test @@ -324,25 +327,27 @@ public class PrivateTransactionTest { assertThat(p).isEqualTo(VALID_SIGNED_PRIVATE_TRANSACTION_LARGE_CHAINID); } - @Test(expected = IllegalArgumentException.class) + @Test public void testBuildInvalidPrivateTransactionThrowsException() { - PrivateTransaction.builder() - .nonce(0) - .gasPrice(Wei.of(1000)) - .gasLimit(3000000) - .to(Address.fromHexString("0x627306090abab3a6e1400e9345bc60c78a8bef57")) - .value(Wei.ZERO) - .payload(Bytes.fromHexString("0x")) - .sender(Address.fromHexString("0xfe3b557e8fb62b89f4916b721be55ceb828dbd73")) - .chainId(BigInteger.valueOf(1337)) - .privacyGroupId(Bytes.fromBase64String("DyAOiF/ynpc+JXa2YAGB0bCitSlOMNm+ShmB/7M6C4w=")) - .privateFrom(Bytes.fromBase64String("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo=")) - .privateFor( - Lists.newArrayList( - Bytes.fromBase64String("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo="), - Bytes.fromBase64String("Ko2bVqD+nNlNYL5EE7y3IdOnviftjiizpjRt+HTuFBs="))) - .restriction(RESTRICTED) - .build(); + final PrivateTransaction.Builder privateTransactionBuilder = + PrivateTransaction.builder() + .nonce(0) + .gasPrice(Wei.of(1000)) + .gasLimit(3000000) + .to(Address.fromHexString("0x627306090abab3a6e1400e9345bc60c78a8bef57")) + .value(Wei.ZERO) + .payload(Bytes.fromHexString("0x")) + .sender(Address.fromHexString("0xfe3b557e8fb62b89f4916b721be55ceb828dbd73")) + .chainId(BigInteger.valueOf(1337)) + .privacyGroupId(Bytes.fromBase64String("DyAOiF/ynpc+JXa2YAGB0bCitSlOMNm+ShmB/7M6C4w=")) + .privateFrom(Bytes.fromBase64String("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo=")) + .privateFor( + Lists.newArrayList( + Bytes.fromBase64String("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo="), + Bytes.fromBase64String("Ko2bVqD+nNlNYL5EE7y3IdOnviftjiizpjRt+HTuFBs="))) + .restriction(RESTRICTED); + assertThatThrownBy(privateTransactionBuilder::build) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/AddressTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/AddressTest.java index 6959ea33e8..b496bb5f6c 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/AddressTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/AddressTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.vm; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.datatypes.Address; @@ -50,18 +51,21 @@ public class AddressTest { assertThat(addr2.hashCode()).isEqualTo(addr.hashCode()); } - @Test(expected = IllegalArgumentException.class) + @Test public void invalidAccountAddress() { - Address.wrap(Bytes.fromHexString("0x00101010")); + final Bytes bytes = Bytes.fromHexString("0x00101010"); + assertThatThrownBy(() -> Address.wrap(bytes)).isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void tooShortAccountAddress() { - Address.fromHexStringStrict("0x00101010"); + assertThatThrownBy(() -> Address.fromHexStringStrict("0x00101010")) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void nullAccountAddress() { - Address.fromHexStringStrict(null); + assertThatThrownBy(() -> Address.fromHexStringStrict(null)) + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/OperandStackTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/OperandStackTest.java index 4cc864228a..95edcc54b9 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/OperandStackTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/OperandStackTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.vm; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.evm.internal.FixedStack.OverflowException; import org.hyperledger.besu.evm.internal.FixedStack.UnderflowException; @@ -32,22 +33,23 @@ public class OperandStackTest { assertThat(stack.size()).isEqualTo(0); } - @Test(expected = IllegalArgumentException.class) + @Test public void construction_NegativeMaximumSize() { - new OperandStack(-1); + assertThatThrownBy(() -> new OperandStack(-1)).isInstanceOf(IllegalArgumentException.class); } - @Test(expected = OverflowException.class) + @Test public void push_StackOverflow() { final OperandStack stack = new OperandStack(1); stack.push(UInt256.fromHexString("0x01")); - stack.push(UInt256.fromHexString("0x02")); + final UInt256 operand = UInt256.fromHexString("0x02"); + assertThatThrownBy(() -> stack.push(operand)).isInstanceOf(OverflowException.class); } - @Test(expected = UnderflowException.class) + @Test public void pop_StackUnderflow() { final OperandStack stack = new OperandStack(1); - stack.pop(); + assertThatThrownBy(stack::pop).isInstanceOf(UnderflowException.class); } @Test @@ -58,17 +60,17 @@ public class OperandStackTest { assertThat(stack.pop()).isEqualTo(Bytes32.fromHexString("0x01")); } - @Test(expected = UnderflowException.class) + @Test public void get_NegativeOffset() { final OperandStack stack = new OperandStack(1); - stack.get(-1); + assertThatThrownBy(() -> stack.get(-1)).isInstanceOf(UnderflowException.class); } - @Test(expected = UnderflowException.class) + @Test public void get_IndexGreaterThanSize() { final OperandStack stack = new OperandStack(1); stack.push(UInt256.fromHexString("0x01")); - stack.get(2); + assertThatThrownBy(() -> stack.get(2)).isInstanceOf(UnderflowException.class); } @Test @@ -83,17 +85,19 @@ public class OperandStackTest { assertThat(stack.get(2)).isEqualTo(Bytes32.fromHexString("0x01")); } - @Test(expected = UnderflowException.class) + @Test public void set_NegativeOffset() { final OperandStack stack = new OperandStack(1); - stack.get(-1); + final Bytes32 operand = Bytes32.fromHexString("0x01"); + assertThatThrownBy(() -> stack.set(-1, operand)).isInstanceOf(IndexOutOfBoundsException.class); } - @Test(expected = UnderflowException.class) + @Test public void set_IndexGreaterThanSize() { final OperandStack stack = new OperandStack(1); stack.push(UInt256.fromHexString("0x01")); - stack.get(2); + final Bytes32 operand = Bytes32.fromHexString("0x01"); + assertThatThrownBy(() -> stack.set(2, operand)).isInstanceOf(IndexOutOfBoundsException.class); } @Test diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java index ca85e6048c..8d67d051d7 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.eth.manager; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryBlockchain; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -88,6 +89,7 @@ import java.util.stream.Collectors; import com.google.common.collect.Lists; import org.apache.tuweni.bytes.Bytes; import org.awaitility.Awaitility; +import org.awaitility.core.ConditionFactory; import org.awaitility.core.ConditionTimeoutException; import org.junit.BeforeClass; import org.junit.Test; @@ -247,7 +249,7 @@ public final class EthProtocolManagerTest { } } - @Test(expected = ConditionTimeoutException.class) + @Test public void doNotDisconnectOnValidMessage() { try (final EthProtocolManager ethManager = EthProtocolManagerTestUtil.create( @@ -260,10 +262,10 @@ public final class EthProtocolManagerTest { GetBlockBodiesMessage.create(Collections.singletonList(gen.hash())); final MockPeerConnection peer = setupPeer(ethManager, (cap, msg, conn) -> {}); ethManager.processMessage(EthProtocol.ETH63, new DefaultMessage(peer, messageData)); - Awaitility.await() - .catchUncaughtExceptions() - .atMost(200, TimeUnit.MILLISECONDS) - .until(peer::isDisconnected); + final ConditionFactory waitDisconnect = + Awaitility.await().catchUncaughtExceptions().atMost(200, TimeUnit.MILLISECONDS); + assertThatThrownBy(() -> waitDisconnect.until(peer::isDisconnected)) + .isInstanceOf(ConditionTimeoutException.class); } } diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastDownloaderFactoryTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastDownloaderFactoryTest.java index a3bc035f9b..7cdcd8d3dc 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastDownloaderFactoryTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastDownloaderFactoryTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.eth.sync.fastsync; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -62,22 +63,25 @@ public class FastDownloaderFactoryTest { @Mock private PivotBlockSelector pivotBlockSelector; @SuppressWarnings("unchecked") - @Test(expected = IllegalStateException.class) + @Test public void shouldThrowIfSyncModeChangedWhileFastSyncIncomplete() { initDataDirectory(true); when(syncConfig.getSyncMode()).thenReturn(SyncMode.FULL); - FastDownloaderFactory.create( - pivotBlockSelector, - syncConfig, - dataDirectory, - protocolSchedule, - protocolContext, - metricsSystem, - ethContext, - worldStateStorage, - syncState, - clock); + assertThatThrownBy( + () -> + FastDownloaderFactory.create( + pivotBlockSelector, + syncConfig, + dataDirectory, + protocolSchedule, + protocolContext, + metricsSystem, + ethContext, + worldStateStorage, + syncState, + clock)) + .isInstanceOf(IllegalStateException.class); } @SuppressWarnings({"unchecked", "rawtypes"}) diff --git a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryPacketSedesTest.java b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryPacketSedesTest.java index c2b7949d2e..14fbb8ea34 100644 --- a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryPacketSedesTest.java +++ b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryPacketSedesTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.p2p.discovery; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.data.Offset.offset; import org.hyperledger.besu.crypto.NodeKey; @@ -26,6 +27,7 @@ import org.hyperledger.besu.ethereum.p2p.discovery.internal.PacketData; import org.hyperledger.besu.ethereum.p2p.discovery.internal.PacketType; import org.hyperledger.besu.ethereum.rlp.RLP; import org.hyperledger.besu.ethereum.rlp.RLPException; +import org.hyperledger.besu.ethereum.rlp.RLPInput; import java.util.List; import java.util.Random; @@ -90,7 +92,7 @@ public class PeerDiscoveryPacketSedesTest { assertThat(deserialized.getExpiration()).isCloseTo(PacketData.defaultExpiration(), offset(2L)); } - @Test(expected = RLPException.class) + @Test public void deserializeDifferentPacketData() { final byte[] r = new byte[64]; new Random().nextBytes(r); @@ -100,10 +102,11 @@ public class PeerDiscoveryPacketSedesTest { final Bytes serialized = RLP.encode(packet::writeTo); assertThat(serialized).isNotNull(); - NeighborsPacketData.readFrom(RLP.input(serialized)); + final RLPInput input = RLP.input(serialized); + assertThatThrownBy(() -> NeighborsPacketData.readFrom(input)).isInstanceOf(RLPException.class); } - @Test(expected = PeerDiscoveryPacketDecodingException.class) + @Test public void integrityCheckFailsUnmatchedHash() { final byte[] r = new byte[64]; new Random().nextBytes(r); @@ -120,6 +123,8 @@ public class PeerDiscoveryPacketSedesTest { // Change one bit in the last byte, which belongs to the payload, hence the hash will not match // any longer. garbled.set(i, (byte) (garbled.get(i) + 0x01)); - Packet.decode(Buffer.buffer(garbled.toArray())); + final Buffer input = Buffer.buffer(garbled.toArray()); + assertThatThrownBy(() -> Packet.decode(input)) + .isInstanceOf(PeerDiscoveryPacketDecodingException.class); } } diff --git a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PacketTest.java b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PacketTest.java index e6130fc40f..eeef2d4ddb 100644 --- a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PacketTest.java +++ b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PacketTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.p2p.discovery.internal; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.ethereum.p2p.discovery.Endpoint; import org.hyperledger.besu.ethereum.p2p.discovery.PeerDiscoveryPacketDecodingException; @@ -65,9 +66,10 @@ public class PacketTest { assertThat(Hex.toHexString(packet.encode().getBytes())).isEqualTo(VALID_PONG_PACKET); } - @Test(expected = PeerDiscoveryPacketDecodingException.class) + @Test public void invalidSignatureShouldThrowPeerDiscoveryPacketDecodingException() { - decode(INVALID_SIGNATURE_PACKET); + assertThatThrownBy(() -> decode(INVALID_SIGNATURE_PACKET)) + .isInstanceOf(PeerDiscoveryPacketDecodingException.class); } private Packet decode(final String hexData) { diff --git a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerDistanceCalculatorTest.java b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerDistanceCalculatorTest.java index f97e233e14..f4634c15ea 100644 --- a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerDistanceCalculatorTest.java +++ b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerDistanceCalculatorTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.p2p.discovery.internal; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.ethereum.p2p.discovery.internal.PeerDistanceCalculator.distance; import java.util.Random; @@ -66,11 +67,11 @@ public class PeerDiscoveryControllerDistanceCalculatorTest { assertThat(distance(id1, id2)).isEqualTo(40); } - @Test(expected = AssertionError.class) + @Test public void distance40_differentLengths() { final Bytes id1 = Bytes.fromHexString("0x8f19400000"); final Bytes id2 = Bytes.fromHexString("0x0f1940000099"); - assertThat(distance(id1, id2)).isEqualTo(40); + assertThatThrownBy(() -> distance(id1, id2)).isInstanceOf(AssertionError.class); } @Test diff --git a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java index e632b70c6a..5a9377bf5c 100644 --- a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java +++ b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.ethereum.p2p.discovery.internal; import static com.google.common.base.Preconditions.checkNotNull; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.argThat; @@ -600,10 +601,10 @@ public class PeerDiscoveryControllerTest { .send(eq(peers.get(2)), matchPacketOfType(PacketType.PING)); } - @Test(expected = IllegalStateException.class) + @Test public void startTwice() { startPeerDiscoveryController(); - controller.start(); + assertThatThrownBy(() -> controller.start()).isInstanceOf(IllegalStateException.class); } @Test diff --git a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/NetworkingServiceLifecycleTest.java b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/NetworkingServiceLifecycleTest.java index 35d8bba7db..715eb43143 100644 --- a/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/NetworkingServiceLifecycleTest.java +++ b/ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/NetworkingServiceLifecycleTest.java @@ -16,6 +16,7 @@ package org.hyperledger.besu.ethereum.p2p.network; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.ethereum.p2p.NetworkingTestHelper.configWithRandomPorts; import org.hyperledger.besu.crypto.NodeKey; @@ -65,41 +66,56 @@ public class NetworkingServiceLifecycleTest { } } - @Test(expected = IllegalArgumentException.class) + @Test public void createP2PNetwork_NullHost() throws IOException { final NetworkingConfiguration config = NetworkingConfiguration.create() .setDiscovery(DiscoveryConfiguration.create().setBindHost(null)); - try (final P2PNetwork broken = builder().config(config).build()) { - Assertions.fail("Expected Exception"); - } + final DefaultP2PNetwork.Builder p2pNetworkBuilder = builder().config(config); + assertThatThrownBy( + () -> { + try (final P2PNetwork ignored = p2pNetworkBuilder.build()) { + Assertions.fail("Expected Exception"); + } + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void createP2PNetwork_InvalidHost() throws IOException { final NetworkingConfiguration config = NetworkingConfiguration.create() .setDiscovery(DiscoveryConfiguration.create().setBindHost("fake.fake.fake")); - try (final P2PNetwork broken = builder().config(config).build()) { - Assertions.fail("Expected Exception"); - } + final DefaultP2PNetwork.Builder p2pNetworkBuilder = builder().config(config); + assertThatThrownBy( + () -> { + try (final P2PNetwork ignored = p2pNetworkBuilder.build()) { + Assertions.fail("Expected Exception"); + } + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = IllegalArgumentException.class) + @Test public void createP2PNetwork_InvalidPort() throws IOException { final NetworkingConfiguration config = NetworkingConfiguration.create() .setDiscovery(DiscoveryConfiguration.create().setBindPort(-1)); - try (final P2PNetwork broken = builder().config(config).build()) { - Assertions.fail("Expected Exception"); - } + final DefaultP2PNetwork.Builder p2pNetworkBuilder = builder().config(config); + assertThatThrownBy( + () -> { + try (final P2PNetwork ignored = p2pNetworkBuilder.build()) { + Assertions.fail("Expected Exception"); + } + }) + .isInstanceOf(IllegalArgumentException.class); } - @Test(expected = NullPointerException.class) + @Test public void createP2PNetwork_NullKeyPair() throws IOException { - try (final P2PNetwork broken = builder().config(config).nodeKey(null).build()) { - Assertions.fail("Expected Exception"); - } + final DefaultP2PNetwork.Builder p2pNetworkBuilder = builder().config(config); + assertThatThrownBy(() -> p2pNetworkBuilder.nodeKey(null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/BytesValueRLPOutputTest.java b/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/BytesValueRLPOutputTest.java index 8432c38863..12f0d4948e 100644 --- a/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/BytesValueRLPOutputTest.java +++ b/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/BytesValueRLPOutputTest.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.rlp; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.units.bigints.UInt256; @@ -153,11 +154,11 @@ public class BytesValueRLPOutputTest { assertThat(out.encoded()).isEqualTo(h("0xbb01000000" + times("3c", 16777216))); } - @Test(expected = IllegalStateException.class) + @Test public void multipleElementAddedWithoutList() { final BytesValueRLPOutput out = new BytesValueRLPOutput(); out.writeByte((byte) 0); - out.writeByte((byte) 1); + assertThatThrownBy(() -> out.writeByte((byte) 1)).isInstanceOf(IllegalStateException.class); } @Test @@ -203,17 +204,17 @@ public class BytesValueRLPOutputTest { assertThat(out.encoded()).isEqualTo(h("0xc0")); } - @Test(expected = IllegalStateException.class) + @Test public void unclosedList() { final BytesValueRLPOutput out = new BytesValueRLPOutput(); out.startList(); - out.encoded(); + assertThatThrownBy(out::encoded).isInstanceOf(IllegalStateException.class); } - @Test(expected = IllegalStateException.class) + @Test public void closeUnopenedList() { final BytesValueRLPOutput out = new BytesValueRLPOutput(); - out.endList(); + assertThatThrownBy(out::endList).isInstanceOf(IllegalStateException.class); } @Test diff --git a/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/InvalidRLPRefTest.java b/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/InvalidRLPRefTest.java index 66ef4ca298..bb55cd0b93 100644 --- a/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/InvalidRLPRefTest.java +++ b/ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/InvalidRLPRefTest.java @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.ethereum.rlp; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assume.assumeTrue; import org.hyperledger.besu.ethereum.rlp.util.RLPTestUtil; @@ -21,6 +22,7 @@ import org.hyperledger.besu.testutil.JsonTestParameters; import java.util.Collection; +import org.apache.tuweni.bytes.Bytes; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -49,8 +51,9 @@ public class InvalidRLPRefTest { } /** Test RLP decoding. */ - @Test(expected = RLPException.class) + @Test public void decode() throws Exception { - RLPTestUtil.decode(spec.getRLP()); + final Bytes rlp = spec.getRLP(); + assertThatThrownBy(() -> RLPTestUtil.decode(rlp)).isInstanceOf(RLPException.class); } } diff --git a/ethereum/trie/src/test/java/org/hyperledger/besu/ethereum/trie/AbstractMerklePatriciaTrieTest.java b/ethereum/trie/src/test/java/org/hyperledger/besu/ethereum/trie/AbstractMerklePatriciaTrieTest.java index ef45ea4b8f..b8e454fef6 100644 --- a/ethereum/trie/src/test/java/org/hyperledger/besu/ethereum/trie/AbstractMerklePatriciaTrieTest.java +++ b/ethereum/trie/src/test/java/org/hyperledger/besu/ethereum/trie/AbstractMerklePatriciaTrieTest.java @@ -17,6 +17,7 @@ package org.hyperledger.besu.ethereum.trie; import static java.nio.charset.StandardCharsets.UTF_8; import static junit.framework.TestCase.assertFalse; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.plugin.services.storage.KeyValueStorage; import org.hyperledger.besu.services.kvstore.InMemoryKeyValueStorage; @@ -50,9 +51,10 @@ public abstract class AbstractMerklePatriciaTrieTest { .isEqualTo("0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421"); } - @Test(expected = NullPointerException.class) + @Test public void throwsOnUpdateWithNull() { - trie.put(Bytes.EMPTY, (String) null); + assertThatThrownBy(() -> trie.put(Bytes.EMPTY, (String) null)) + .isInstanceOf(NullPointerException.class); } @Test diff --git a/nat/src/test/java/org/hyperledger/besu/nat/kubernetes/KubernetesUnknownNatManagerTest.java b/nat/src/test/java/org/hyperledger/besu/nat/kubernetes/KubernetesUnknownNatManagerTest.java index e72cadeac5..fb180fde81 100644 --- a/nat/src/test/java/org/hyperledger/besu/nat/kubernetes/KubernetesUnknownNatManagerTest.java +++ b/nat/src/test/java/org/hyperledger/besu/nat/kubernetes/KubernetesUnknownNatManagerTest.java @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.nat.kubernetes; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.nat.kubernetes.KubernetesNatManager.DEFAULT_BESU_SERVICE_NAME_FILTER; import static org.mockito.Mockito.when; @@ -47,8 +48,9 @@ public final class KubernetesUnknownNatManagerTest { } } - @Test(expected = RuntimeException.class) + @Test public void assertThatNatExceptionIsThrownWithUnknownServiceType() { - natManager.updateUsingBesuService(v1Service); + assertThatThrownBy(() -> natManager.updateUsingBesuService(v1Service)) + .isInstanceOf(RuntimeException.class); } } diff --git a/pki/src/test/java/org/hyperledger/besu/pki/keystore/HardwareKeyStoreFileWrapperTest.java b/pki/src/test/java/org/hyperledger/besu/pki/keystore/HardwareKeyStoreFileWrapperTest.java index 3e444b125c..99208e01c5 100644 --- a/pki/src/test/java/org/hyperledger/besu/pki/keystore/HardwareKeyStoreFileWrapperTest.java +++ b/pki/src/test/java/org/hyperledger/besu/pki/keystore/HardwareKeyStoreFileWrapperTest.java @@ -14,6 +14,8 @@ */ package org.hyperledger.besu.pki.keystore; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + import org.hyperledger.besu.pki.PkiException; import java.nio.file.Path; @@ -78,11 +80,12 @@ public class HardwareKeyStoreFileWrapperTest extends BaseKeyStoreFileWrapperTest CryptoTestUtil.isNSSLibInstalled()); } - @Test(expected = IllegalArgumentException.class) + @Test public void getPkcs11Provider() throws Exception { final HardwareKeyStoreWrapper sut = (HardwareKeyStoreWrapper) getHardwareKeyStoreWrapper(configName); - sut.getPkcs11ProviderForConfig("no-library"); + assertThatThrownBy(() -> sut.getPkcs11ProviderForConfig("no-library")) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -90,20 +93,24 @@ public class HardwareKeyStoreFileWrapperTest extends BaseKeyStoreFileWrapperTest new HardwareKeyStoreWrapper(validKeystorePassword, toPath(config), toPath(crl)); } - @Test(expected = NullPointerException.class) + @Test public void init_keystorePassword_config_invalid() throws Exception { final String config = "invalid"; - new HardwareKeyStoreWrapper(validKeystorePassword, toPath(config), toPath(crl)); + assertThatThrownBy( + () -> new HardwareKeyStoreWrapper(validKeystorePassword, toPath(config), toPath(crl))) + .isInstanceOf(NullPointerException.class); } - @Test(expected = PkiException.class) + @Test public void init_keystorePassword_config_missing_pw() throws Exception { - new HardwareKeyStoreWrapper(null, toPath(config), toPath(crl)); + assertThatThrownBy(() -> new HardwareKeyStoreWrapper(null, toPath(config), toPath(crl))) + .isInstanceOf(PkiException.class); } - @Test(expected = PkiException.class) + @Test public void init_keystorePassword_provider_missing_pw() throws Exception { final Provider p = null; - new HardwareKeyStoreWrapper(validKeystorePassword, p, toPath(crl)); + assertThatThrownBy(() -> new HardwareKeyStoreWrapper(validKeystorePassword, p, toPath(crl))) + .isInstanceOf(PkiException.class); } }