Replace expected Junit 4 @Test field with assertThatThrownBy (#3814)

* Fix two operand stack tests

Signed-off-by: Diego López León <dieguitoll@gmail.com>

* Remove unreachable assert

Signed-off-by: Diego López León <dieguitoll@gmail.com>

* Replace expected annotation field with assert

Signed-off-by: Diego López León <dieguitoll@gmail.com>

* Extract variables to let only a single call for assert

Signed-off-by: Diego López León <dieguitoll@gmail.com>

Co-authored-by: Sally MacFarlane <sally.macfarlane@consensys.net>
pull/3821/head
Diego López León 3 years ago committed by GitHub
parent 3820b584b5
commit 2cf97a0e67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/PrivateContractPublicStateAcceptanceTest.java
  2. 17
      acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/contracts/PrivacyGroupTest.java
  3. 19
      besu/src/test/java/org/hyperledger/besu/cli/operator/OperatorSubCommandTest.java
  4. 6
      besu/src/test/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOptionTest.java
  5. 11
      consensus/ibftlegacy/src/test/java/org/hyperledger/besu/consensus/ibftlegacy/BftExtraDataCodecTest.java
  6. 32
      crypto/src/test/java/org/hyperledger/besu/crypto/Blake2bfMessageDigestTest.java
  7. 12
      crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairTest.java
  8. 8
      crypto/src/test/java/org/hyperledger/besu/crypto/KeyPairUtilTest.java
  9. 11
      crypto/src/test/java/org/hyperledger/besu/crypto/SECP256K1Test.java
  10. 11
      crypto/src/test/java/org/hyperledger/besu/crypto/SECP256R1Test.java
  11. 6
      crypto/src/test/java/org/hyperledger/besu/crypto/SECPPrivateKeyTest.java
  12. 18
      crypto/src/test/java/org/hyperledger/besu/crypto/SECPPublicKeyTest.java
  13. 11
      crypto/src/test/java/org/hyperledger/besu/crypto/SECPSignatureTest.java
  14. 7
      crypto/src/test/java/org/hyperledger/besu/crypto/SignatureAlgorithmFactoryTest.java
  15. 6
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonResponseStreamerTest.java
  16. 16
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/authentication/EngineAuthServiceTest.java
  17. 6
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCacheTest.java
  18. 6
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCacheTest.java
  19. 5
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/JsonResponseStreamerTest.java
  20. 15
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchainTest.java
  21. 5
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/FlexiblePrivacyPrecompiledContractTest.java
  22. 5
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/precompiles/privacy/PrivacyPrecompiledContractTest.java
  23. 15
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerOnchainTest.java
  24. 9
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/MultiTenancyPrivacyControllerTest.java
  25. 45
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/privacy/PrivateTransactionTest.java
  26. 16
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/AddressTest.java
  27. 32
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/OperandStackTest.java
  28. 12
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java
  29. 28
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fastsync/FastDownloaderFactoryTest.java
  30. 13
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryPacketSedesTest.java
  31. 6
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PacketTest.java
  32. 5
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerDistanceCalculatorTest.java
  33. 5
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/internal/PeerDiscoveryControllerTest.java
  34. 48
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/network/NetworkingServiceLifecycleTest.java
  35. 13
      ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/BytesValueRLPOutputTest.java
  36. 7
      ethereum/rlp/src/test/java/org/hyperledger/besu/ethereum/rlp/InvalidRLPRefTest.java
  37. 6
      ethereum/trie/src/test/java/org/hyperledger/besu/ethereum/trie/AbstractMerklePatriciaTrieTest.java
  38. 6
      nat/src/test/java/org/hyperledger/besu/nat/kubernetes/KubernetesUnknownNatManagerTest.java
  39. 23
      pki/src/test/java/org/hyperledger/besu/pki/keystore/HardwareKeyStoreFileWrapperTest.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<BigInteger> functionCall =
publicReader.read(privateEventEmitter.getContractAddress());
assertThatThrownBy(functionCall::send).isInstanceOf(ContractCallException.class);
}
@Test

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -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")));

@ -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<File> 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<File> signingKey = Optional.of(userKey.toFile());
assertThatThrownBy(() -> new EngineAuthService(vertx, signingKey, dataDir))
.isInstanceOf(UnsecurableEngineApiException.class);
}
@Test

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

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

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

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

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

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

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

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

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

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

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

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

@ -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"})

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save