diff --git a/framework/src/main/java/org/tron/common/backup/socket/BackupServer.java b/framework/src/main/java/org/tron/common/backup/socket/BackupServer.java index 67739ac50d2..5cdb35fa945 100644 --- a/framework/src/main/java/org/tron/common/backup/socket/BackupServer.java +++ b/framework/src/main/java/org/tron/common/backup/socket/BackupServer.java @@ -27,7 +27,7 @@ public class BackupServer implements AutoCloseable { private BackupManager backupManager; - private Channel channel; + private volatile Channel channel; private volatile boolean shutdown = false; @@ -77,6 +77,10 @@ public void initChannel(NioDatagramChannel ch) logger.info("Backup server started, bind port {}", port); + // If close() was called while bind() was in progress, channel was not yet visible + if (shutdown) { + break; + } channel.closeFuture().sync(); if (shutdown) { logger.info("Shutdown backup BackupServer"); diff --git a/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java b/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java index 253502bc3a1..ef2c7d5983a 100644 --- a/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java +++ b/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java @@ -57,8 +57,6 @@ @Scope("prototype") public class PeerConnection { - private static List relayNodes = Args.getInstance().getFastForwardNodes(); - @Getter private PeerStatistics peerStatistics = new PeerStatistics(); @@ -163,10 +161,16 @@ public class PeerConnection { private volatile boolean needSyncFromUs = true; @Getter private P2pRateLimiter p2pRateLimiter = new P2pRateLimiter(); + @Getter + private List relayNodes; public void setChannel(Channel channel) { this.channel = channel; - if (relayNodes.stream().anyMatch(n -> n.getAddress().equals(channel.getInetAddress()))) { + if (this.relayNodes == null) { + this.relayNodes = Args.getInstance().getFastForwardNodes(); + } + if (relayNodes != null + && relayNodes.stream().anyMatch(n -> n.getAddress().equals(channel.getInetAddress()))) { this.isRelayPeer = true; } this.nodeStatistics = TronStatsManager.getNodeStatistics(channel.getInetAddress()); diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index 3367141e2a5..f1c5bab0dce 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -2,7 +2,9 @@ import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -11,6 +13,7 @@ import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.client.DatabaseGrpcClient; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.parameter.CommonParameter; import org.tron.common.prometheus.Metrics; import org.tron.core.ChainBaseManager; @@ -39,6 +42,9 @@ public class SolidityNode { private volatile boolean flag = true; + private ExecutorService getBlockEs; + private ExecutorService processBlockEs; + public SolidityNode(Manager dbManager) { this.dbManager = dbManager; this.chainBaseManager = dbManager.getChainBaseManager(); @@ -72,13 +78,25 @@ public static void start() { appT.startup(); SolidityNode node = new SolidityNode(appT.getDbManager()); node.run(); - appT.blockUntilShutdown(); + awaitShutdown(appT, node); + } + + static void awaitShutdown(Application appT, SolidityNode node) { + try { + appT.blockUntilShutdown(); + } finally { + // SolidityNode is created manually rather than managed by Spring/Application, + // so its executors must be shut down explicitly on exit. + node.shutdown(); + } } private void run() { try { - new Thread(this::getBlock).start(); - new Thread(this::processBlock).start(); + getBlockEs = ExecutorServiceManager.newSingleThreadExecutor("solid-get-block"); + processBlockEs = ExecutorServiceManager.newSingleThreadExecutor("solid-process-block"); + getBlockEs.execute(this::getBlock); + processBlockEs.execute(this::processBlock); logger.info("Success to start solid node, ID: {}, remoteBlockNum: {}.", ID.get(), remoteBlockNum); } catch (Exception e) { @@ -88,6 +106,12 @@ private void run() { } } + public void shutdown() { + flag = false; + ExecutorServiceManager.shutdownAndAwaitTermination(getBlockEs, "solid-get-block"); + ExecutorServiceManager.shutdownAndAwaitTermination(processBlockEs, "solid-process-block"); + } + private void getBlock() { long blockNum = ID.incrementAndGet(); while (flag) { @@ -137,7 +161,7 @@ private void loopProcessBlock(Block block) { } private Block getBlockByNum(long blockNum) { - while (true) { + while (flag) { try { long time = System.currentTimeMillis(); Block block = databaseGrpcClient.getBlock(blockNum); @@ -155,10 +179,11 @@ private Block getBlockByNum(long blockNum) { sleep(exceptionSleepTime); } } + return null; } private long getLastSolidityBlockNum() { - while (true) { + while (flag) { try { long time = System.currentTimeMillis(); long blockNum = databaseGrpcClient.getDynamicProperties().getLastSolidityBlockNum(); @@ -171,6 +196,7 @@ private long getLastSolidityBlockNum() { sleep(exceptionSleepTime); } } + return 0; } public void sleep(long time) { @@ -193,4 +219,4 @@ private void resolveCompatibilityIssueIfUsingFullNodeDatabase() { chainBaseManager.getDynamicPropertiesStore().saveLatestSolidifiedBlockNum(headBlockNum); } } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/ClassLevelAppContextFixture.java b/framework/src/test/java/org/tron/common/ClassLevelAppContextFixture.java new file mode 100644 index 00000000000..1d26f895b64 --- /dev/null +++ b/framework/src/test/java/org/tron/common/ClassLevelAppContextFixture.java @@ -0,0 +1,62 @@ +package org.tron.common; + +import io.grpc.ManagedChannel; +import java.util.concurrent.TimeUnit; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.core.config.DefaultConfig; + +/** + * Shared class-level fixture for tests that manually manage a TronApplicationContext. + */ +public class ClassLevelAppContextFixture { + + private TronApplicationContext context; + + public TronApplicationContext createContext() { + context = new TronApplicationContext(DefaultConfig.class); + return context; + } + + public TronApplicationContext createAndStart() { + createContext(); + startApp(); + return context; + } + + public void startApp() { + ApplicationFactory.create(context).startup(); + } + + public TronApplicationContext getContext() { + return context; + } + + public void close() { + if (context != null) { + context.close(); + context = null; + } + } + + public static void shutdownChannel(ManagedChannel channel) { + if (channel == null) { + return; + } + try { + channel.shutdown(); + if (!channel.awaitTermination(5, TimeUnit.SECONDS)) { + channel.shutdownNow(); + } + } catch (InterruptedException e) { + channel.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + + public static void shutdownChannels(ManagedChannel... channels) { + for (ManagedChannel channel : channels) { + shutdownChannel(channel); + } + } +} diff --git a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java index ae5f74d8b71..f9795587032 100644 --- a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java +++ b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java @@ -21,7 +21,7 @@ public class BackupServerTest { public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule - public Timeout globalTimeout = Timeout.seconds(60); + public Timeout globalTimeout = Timeout.seconds(90); private BackupServer backupServer; @Before @@ -43,7 +43,7 @@ public void tearDown() { Args.clearParam(); } - @Test(timeout = 60_000) + @Test public void test() throws InterruptedException { backupServer.initServer(); // wait for the server to start diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java index 34a8e82c424..9b0f17244a8 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java @@ -65,7 +65,6 @@ public synchronized void testEventParser() { for (int i = 0; i < entryArr.size(); i++) { JSONObject e = entryArr.getJSONObject(i); - System.out.println(e.getString("name")); if (e.getString("name") != null) { if (e.getString("name").equalsIgnoreCase("eventBytesL")) { entry = e; diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java index eff644b9cd9..0d2a8ed1496 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java @@ -68,7 +68,6 @@ public synchronized void testEventParser() { ABI.Entry entry = null; for (ABI.Entry e : abi.getEntrysList()) { - System.out.println(e.getName()); if (e.getName().equalsIgnoreCase("eventBytesL")) { entry = e; break; diff --git a/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java b/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java index d356e43d66c..a71b64b0a6d 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/NativeMessageQueueTest.java @@ -1,7 +1,11 @@ package org.tron.common.logsfilter; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import org.junit.After; import org.junit.Assert; import org.junit.Test; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.logsfilter.nativequeue.NativeMessageQueue; import org.zeromq.SocketType; import org.zeromq.ZContext; @@ -13,6 +17,21 @@ public class NativeMessageQueueTest { public String dataToSend = "################"; public String topic = "testTopic"; + private ExecutorService subscriberExecutor; + + @After + public void tearDown() { + if (subscriberExecutor != null) { + subscriberExecutor.shutdownNow(); + try { + subscriberExecutor.awaitTermination(2, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + subscriberExecutor = null; + } + } + @Test public void invalidBindPort() { boolean bRet = NativeMessageQueue.getInstance().start(-1111, 0); @@ -39,7 +58,7 @@ public void publishTrigger() { try { Thread.sleep(1000); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); } NativeMessageQueue.getInstance().publishTrigger(dataToSend, topic); @@ -47,14 +66,15 @@ public void publishTrigger() { try { Thread.sleep(1000); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); } NativeMessageQueue.getInstance().stop(); } public void startSubscribeThread() { - Thread thread = new Thread(() -> { + subscriberExecutor = ExecutorServiceManager.newSingleThreadExecutor("zmq-subscriber"); + subscriberExecutor.execute(() -> { try (ZContext context = new ZContext()) { ZMQ.Socket subscriber = context.createSocket(SocketType.SUB); @@ -70,6 +90,5 @@ public void startSubscribeThread() { // ZMQ.Socket will be automatically closed when ZContext is closed } }); - thread.start(); } } diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java index 5381c6ab2de..b5f7e676eea 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java @@ -22,7 +22,6 @@ public void setUp() { public void testSetAndGetBlockHash() { blockFilterCapsule .setBlockHash("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f"); - System.out.println(blockFilterCapsule); Assert.assertEquals("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", blockFilterCapsule.getBlockHash()); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java index 40a4003f625..8e38c08c4d8 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java @@ -24,6 +24,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.tron.common.BaseTest; +import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.Commons; @@ -153,8 +154,13 @@ public void testSuccess() { @Test public void testSuccessNoBandd() { + boolean originalDebug = CommonParameter.getInstance().isDebug(); try { byte[] contractAddress = createContract(); + // Enable debug mode to bypass CPU time limit check in Program.checkCPUTimeLimit(). + // Without this, the heavy contract execution (setCoin) may exceed the time threshold + // on slow machines and cause the test to fail non-deterministically. + CommonParameter.getInstance().setDebug(true); TriggerSmartContract triggerContract = TvmTestUtils.createTriggerContract(contractAddress, "setCoin(uint256)", "50", false, 0, Commons.decodeFromBase58Check(TriggerOwnerTwoAddress)); @@ -185,6 +191,8 @@ public void testSuccessNoBandd() { balance); } catch (TronException e) { Assert.assertNotNull(e); + } finally { + CommonParameter.getInstance().setDebug(originalDebug); } } @@ -254,4 +262,4 @@ public void testMaxContractResultSize() { } Assert.assertEquals(2, maxSize); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java index 0d6305f8782..071c07bdc9e 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java @@ -289,17 +289,9 @@ public void testWithCallerEnergyChangedInTx() throws Exception { TVMTestResult result = freezeForOther(userA, contractAddr, userA, frozenBalance, 1); - System.out.println(result.getReceipt().getEnergyUsageTotal()); - System.out.println(accountStore.get(userA)); - System.out.println(accountStore.get(owner)); - clearDelegatedExpireTime(contractAddr, userA); result = unfreezeForOther(userA, contractAddr, userA, 1); - - System.out.println(result.getReceipt().getEnergyUsageTotal()); - System.out.println(accountStore.get(userA)); - System.out.println(accountStore.get(owner)); } @Test diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java b/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java index 66de45a0658..75b11f4ab9d 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java @@ -124,8 +124,6 @@ public void testZeroLengthOneArray() { // witness array zero, amount array non-zero Program program = mockProgram(0, 0, 64, 1, 0); long cost = EnergyCost.getVoteWitnessCost3(program); - // witnessArraySize = 0 * 32 + 32 = 32, witnessMemNeeded = 0 + 32 = 32 - // amountArraySize = 1 * 32 + 32 = 64, amountMemNeeded = 64 + 64 = 128 // memWords = 128 / 32 = 4 // memEnergy = 3 * 4 + 4 * 4 / 512 = 12 assertEquals(30012, cost); diff --git a/framework/src/test/java/org/tron/common/utils/PropUtilTest.java b/framework/src/test/java/org/tron/common/utils/PropUtilTest.java index 2df5bd8effd..330d97bd51c 100644 --- a/framework/src/test/java/org/tron/common/utils/PropUtilTest.java +++ b/framework/src/test/java/org/tron/common/utils/PropUtilTest.java @@ -14,7 +14,7 @@ public void testWriteProperty() { try { file.createNewFile(); } catch (IOException e) { - e.printStackTrace(); + Assert.fail(e.getMessage()); } PropUtil.writeProperty(filename, "key", "value"); Assert.assertTrue("value".equals(PropUtil.readProperty(filename, "key"))); @@ -30,11 +30,11 @@ public void testReadProperty() { try { file.createNewFile(); } catch (IOException e) { - e.printStackTrace(); + Assert.fail(e.getMessage()); } PropUtil.writeProperty(filename, "key", "value"); Assert.assertTrue("value".equals(PropUtil.readProperty(filename, "key"))); file.delete(); Assert.assertTrue("".equals(PropUtil.readProperty(filename, "key"))); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/ShieldWalletTest.java b/framework/src/test/java/org/tron/core/ShieldWalletTest.java index 903309510a8..b9fa48dca38 100644 --- a/framework/src/test/java/org/tron/core/ShieldWalletTest.java +++ b/framework/src/test/java/org/tron/core/ShieldWalletTest.java @@ -369,14 +369,12 @@ public void testCreateShieldedContractParameters2() throws ContractExeException Assert.fail(); } - try { - wallet1.createShieldedContractParameters(builder.build()); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("PaymentAddress in ReceiveNote should not be empty", - e.getMessage()); - } + PrivateShieldedTRC20Parameters.Builder finalBuilder = builder; + Exception e1 = Assert.assertThrows(Exception.class, + () -> wallet1.createShieldedContractParameters(finalBuilder.build())); + Assert.assertTrue(e1 instanceof ContractValidateException); + Assert.assertEquals("PaymentAddress in ReceiveNote should not be empty", + e1.getMessage()); String parameter2 = new String(ByteArray.fromHexString( "7b0a202020202261736b223a2263323531336539653330383439343933326264383265306365353336" @@ -402,14 +400,12 @@ public void testCreateShieldedContractParameters2() throws ContractExeException Assert.fail(); } - try { - wallet1.createShieldedContractParameters(builder.build()); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("PaymentAddress in SpendNote should not be empty", - e.getMessage()); - } + PrivateShieldedTRC20Parameters.Builder finalBuilder1 = builder; + Exception e2 = Assert.assertThrows(Exception.class, + () -> wallet1.createShieldedContractParameters(finalBuilder1.build())); + Assert.assertTrue(e2 instanceof ContractValidateException); + Assert.assertEquals("PaymentAddress in SpendNote should not be empty", + e2.getMessage()); } @Test diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 44e25a16387..0df8d6cdc2c 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -860,15 +860,12 @@ public void testGetDelegatedResourceV2() { @Test public void testGetPaginatedNowWitnessList_Error() { - try { - // To avoid throw MaintenanceClearingException - dbManager.getChainBaseManager().getDynamicPropertiesStore().saveStateFlag(1); - wallet.getPaginatedNowWitnessList(0, 10); - Assert.fail("Should throw error when in maintenance period"); - } catch (Exception e) { - Assert.assertTrue("Should throw MaintenanceClearingException", - e instanceof MaintenanceUnavailableException); - } + // To avoid throw MaintenanceClearingException + dbManager.getChainBaseManager().getDynamicPropertiesStore().saveStateFlag(1); + Exception maintenanceEx = Assert.assertThrows(Exception.class, + () -> wallet.getPaginatedNowWitnessList(0, 10)); + Assert.assertTrue("Should throw MaintenanceClearingException", + maintenanceEx instanceof MaintenanceUnavailableException); try { Args.getInstance().setSolidityNode(true); @@ -1376,13 +1373,9 @@ public void testEstimateEnergyOutOfTime() { Args.getInstance().setEstimateEnergy(true); - try { - wallet.estimateEnergy( - contract, trxCap, trxExtBuilder, retBuilder, estimateBuilder); - Assert.fail("EstimateEnergy should throw exception!"); - } catch (Program.OutOfTimeException ignored) { - Assert.assertTrue(true); - } + Assert.assertThrows(Program.OutOfTimeException.class, + () -> wallet.estimateEnergy( + contract, trxCap, trxExtBuilder, retBuilder, estimateBuilder)); } @Test diff --git a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java index ddcb9976200..c830cd091e6 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java @@ -22,7 +22,6 @@ import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.args.Args; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -621,35 +620,6 @@ public void frozenNumTest() { } } - //@Test - public void moreThanFrozenNumber() { - long frozenBalance = 1_000_000_000L; - long duration = 3; - FreezeBalanceActuator actuator = new FreezeBalanceActuator(); - actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContractForBandwidth(OWNER_ADDRESS, frozenBalance, duration)); - - TransactionResultCapsule ret = new TransactionResultCapsule(); - try { - actuator.validate(); - actuator.execute(ret); - } catch (ContractValidateException | ContractExeException e) { - Assert.fail(); - } - try { - actuator.validate(); - actuator.execute(ret); - fail("cannot run here."); - } catch (ContractValidateException e) { - long maxFrozenNumber = ChainConstant.MAX_FROZEN_NUMBER; - Assert.assertEquals("max frozen number is: " + maxFrozenNumber, e.getMessage()); - - } catch (ContractExeException e) { - Assert.fail(); - } - } - - @Test public void commonErrorCheck() { FreezeBalanceActuator actuator = new FreezeBalanceActuator(); diff --git a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java index 24585326110..92e7cfa78ca 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java @@ -268,33 +268,6 @@ public void lessThan1TrxTest() { } } - //@Test - public void moreThanFrozenNumber() { - long frozenBalance = 1_000_000_000L; - FreezeBalanceActuator actuator = new FreezeBalanceActuator(); - actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); - - TransactionResultCapsule ret = new TransactionResultCapsule(); - try { - actuator.validate(); - actuator.execute(ret); - } catch (ContractValidateException | ContractExeException e) { - Assert.fail(); - } - try { - actuator.validate(); - actuator.execute(ret); - fail("cannot run here."); - } catch (ContractValidateException e) { - long maxFrozenNumber = ChainConstant.MAX_FROZEN_NUMBER; - Assert.assertEquals("max frozen number is: " + maxFrozenNumber, e.getMessage()); - } catch (ContractExeException e) { - Assert.fail(); - } - } - - @Test public void commonErrorCheck() { FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); diff --git a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java index 4c6b7b58b89..dd2a663423e 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java @@ -187,12 +187,9 @@ public void invalidOwnerAddress() { actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( OWNER_ADDRESS_INVALID, orderId)); - try { - actuator.validate(); - Assert.fail("Invalid address"); - } catch (ContractValidateException e) { - Assert.assertEquals("Invalid address", e.getMessage()); - } + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("Invalid address", e.getMessage()); } /** @@ -207,12 +204,9 @@ public void notExistAccount() { actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( OWNER_ADDRESS_NOT_EXIST, orderId)); - try { - actuator.validate(); - Assert.fail("Account does not exist!"); - } catch (ContractValidateException e) { - Assert.assertEquals("Account does not exist!", e.getMessage()); - } + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("Account does not exist!", e.getMessage()); } /** @@ -226,12 +220,9 @@ public void notExistOrder() { MarketCancelOrderActuator actuator = new MarketCancelOrderActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( OWNER_ADDRESS_FIRST, orderId)); - try { - actuator.validate(); - Assert.fail("orderId not exists"); - } catch (ContractValidateException e) { - Assert.assertEquals("orderId not exists", e.getMessage()); - } + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("orderId not exists", e.getMessage()); } /** @@ -260,12 +251,9 @@ public void orderNotActive() throws Exception { actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( OWNER_ADDRESS_FIRST, orderId)); - try { - actuator.validate(); - Assert.fail("Order is not active!"); - } catch (ContractValidateException e) { - Assert.assertEquals("Order is not active!", e.getMessage()); - } + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("Order is not active!", e.getMessage()); } diff --git a/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java index f3211c8b8eb..344a4e95f30 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java @@ -464,29 +464,25 @@ public void testLockedUnDelegateBalanceForBandwidthInsufficient() { actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); - try { - ownerCapsule = dbManager.getAccountStore().get(owner); - Assert.assertEquals(delegateBalance, - receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); - Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); - Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); - Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); - DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() - .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); - DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() - .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); - Assert.assertNull(delegatedResourceCapsule); - Assert.assertNotNull(lockedResourceCapsule); - - actuator.validate(); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("insufficient delegatedFrozenBalance(BANDWIDTH), " - + "request=1000000000, unlock_balance=0", e.getMessage()); - } + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNull(delegatedResourceCapsule); + Assert.assertNotNull(lockedResourceCapsule); + + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("insufficient delegatedFrozenBalance(BANDWIDTH), " + + "request=1000000000, unlock_balance=0", e.getMessage()); } @Test @@ -976,22 +972,16 @@ public void noDelegateBalance() { actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); - try { - actuator.validate(); - Assert.fail("cannot run here."); - } catch (ContractValidateException e) { - Assert.assertEquals("delegated Resource does not exist", e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("delegated Resource does not exist", e1.getMessage()); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getDelegatedContractForCpu(delegateBalance)); - try { - actuator.validate(); - Assert.fail("cannot run here."); - } catch (ContractValidateException e) { - Assert.assertEquals("delegated Resource does not exist", e.getMessage()); - } + ContractValidateException e2 = + Assert.assertThrows(ContractValidateException.class, () -> actuator.validate()); + Assert.assertEquals("delegated Resource does not exist", e2.getMessage()); } @Test diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java index f5c65bf381f..7f74ee3fcc5 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java @@ -1166,12 +1166,9 @@ public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContractForTronPower(OWNER_ADDRESS)); - try { - actuator.validate(); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals("It's not time to unfreeze(TronPower).", e.getMessage()); - } + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); + Assert.assertEquals("It's not time to unfreeze(TronPower).", e.getMessage()); } } diff --git a/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java index 6ec72043722..9823c3aba51 100644 --- a/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java @@ -569,12 +569,8 @@ public void voteWitnessWithoutEnoughOldTronPowerAfterNewResourceModel() { actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContract(OWNER_ADDRESS, WITNESS_ADDRESS, 100L)); TransactionResultCapsule ret = new TransactionResultCapsule(); - try { - actuator.validate(); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - } + Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(0L); } @@ -658,12 +654,8 @@ public void voteWitnessWithoutEnoughOldAndNewTronPowerAfterNewResourceModel() { actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContract(OWNER_ADDRESS, WITNESS_ADDRESS, 4000000L)); TransactionResultCapsule ret = new TransactionResultCapsule(); - try { - actuator.validate(); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - } + Assert.assertThrows(ContractValidateException.class, + () -> actuator.validate()); dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(0L); } diff --git a/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java b/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java index f8d8e6bdd9d..c26da5a7bf7 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java @@ -62,15 +62,12 @@ public void validProposalTypeCheck() throws ContractValidateException { Assert.assertNull(ProposalType.getEnumOrNull(-2)); Assert.assertEquals(ProposalType.ALLOW_TVM_SOLIDITY_059, ProposalType.getEnumOrNull(32)); - long code = -1; - try { - ProposalType.getEnum(code); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals("Does not support code : " + code, e.getMessage()); - } + long finalCode = -1; + ContractValidateException e = Assert.assertThrows(ContractValidateException.class, + () -> ProposalType.getEnum(finalCode)); + Assert.assertEquals("Does not support code : " + finalCode, e.getMessage()); - code = 32; + long code = 32; Assert.assertEquals(ProposalType.ALLOW_TVM_SOLIDITY_059, ProposalType.getEnum(code)); } @@ -79,217 +76,145 @@ public void validProposalTypeCheck() throws ContractValidateException { public void validateCheck() { long invalidValue = -1; - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ACCOUNT_UPGRADE_COST.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ACCOUNT_UPGRADE_COST.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CREATE_ACCOUNT_FEE.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CREATE_ACCOUNT_FEE.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ASSET_ISSUE_FEE.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ASSET_ISSUE_FEE.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), invalidValue); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), LONG_VALUE + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 3 * 27 * 1000 - 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", - e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 24 * 3600 * 1000 + 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", - e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_CREATION_OF_CONTRACTS.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_CREATION_OF_CONTRACTS] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ACCOUNT_UPGRADE_COST.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e1.getMessage()); + + ContractValidateException e2 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ACCOUNT_UPGRADE_COST.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e2.getMessage()); + + ContractValidateException e3 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CREATE_ACCOUNT_FEE.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e3.getMessage()); + + ContractValidateException e4 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CREATE_ACCOUNT_FEE.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e4.getMessage()); + + ContractValidateException e5 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ASSET_ISSUE_FEE.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e5.getMessage()); + + ContractValidateException e6 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ASSET_ISSUE_FEE.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e6.getMessage()); + + ContractValidateException e7 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e7.getMessage()); + + ContractValidateException e8 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e8.getMessage()); + + ContractValidateException e9 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e9.getMessage()); + + ContractValidateException e10 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e10.getMessage()); + + ContractValidateException e11 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e11.getMessage()); + + ContractValidateException e12 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e12.getMessage()); + + ContractValidateException e13 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), invalidValue)); + Assert.assertEquals(LONG_VALUE_ERROR, e13.getMessage()); + + ContractValidateException e14 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), LONG_VALUE + 1)); + Assert.assertEquals(LONG_VALUE_ERROR, e14.getMessage()); + + ContractValidateException e15 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 3 * 27 * 1000 - 1)); + Assert.assertEquals( + "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", + e15.getMessage()); + + ContractValidateException e16 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 24 * 3600 * 1000 + 1)); + Assert.assertEquals( + "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", + e16.getMessage()); + + ContractValidateException e17 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_CREATION_OF_CONTRACTS.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_CREATION_OF_CONTRACTS] is only allowed to be 1", + e17.getMessage()); dynamicPropertiesStore = dbManager.getDynamicPropertiesStore(); dynamicPropertiesStore.saveRemoveThePowerOfTheGr(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[REMOVE_THE_POWER_OF_THE_GR] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e18 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 2)); + Assert.assertEquals( + "This value[REMOVE_THE_POWER_OF_THE_GR] is only allowed to be 1", + e18.getMessage()); dynamicPropertiesStore.saveRemoveThePowerOfTheGr(-1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This proposal has been executed before and is only allowed to be executed once", - e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 9); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter value, valid range is [10,100]", e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 101); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter value, valid range is [10,100]", e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_DELEGATE_RESOURCE.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_DELEGATE_RESOURCE] is only allowed to be 1", e.getMessage()); - } + ContractValidateException e19 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 1)); + Assert.assertEquals( + "This proposal has been executed before and is only allowed to be executed once", + e19.getMessage()); + + ContractValidateException e20 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 9)); + Assert.assertEquals( + "Bad chain parameter value, valid range is [10,100]", e20.getMessage()); + + ContractValidateException e21 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 101)); + Assert.assertEquals( + "Bad chain parameter value, valid range is [10,100]", e21.getMessage()); + + ContractValidateException e22 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_DELEGATE_RESOURCE.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_DELEGATE_RESOURCE] is only allowed to be 1", e22.getMessage()); dynamicPropertiesStore.saveAllowSameTokenName(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_TVM_TRANSFER_TRC10] is only allowed to be 1", e.getMessage()); - } + ContractValidateException e23 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_TVM_TRANSFER_TRC10] is only allowed to be 1", e23.getMessage()); dynamicPropertiesStore.saveAllowSameTokenName(0); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals("[ALLOW_SAME_TOKEN_NAME] proposal must be approved " - + "before [ALLOW_TVM_TRANSFER_TRC10] can be proposed", e.getMessage()); - } + ContractValidateException e24 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 1)); + Assert.assertEquals("[ALLOW_SAME_TOKEN_NAME] proposal must be approved " + + "before [ALLOW_TVM_TRANSFER_TRC10] can be proposed", e24.getMessage()); forkUtils.init(dbManager.getChainBaseManager()); long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() @@ -308,15 +233,12 @@ public void validateCheck() { List w = new ArrayList<>(); w.add(address); forkUtils.getManager().getWitnessScheduleStore().saveActiveWitnesses(w); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_SHIELDED_TRC20_TRANSACTION - .getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals("This value[ALLOW_SHIELDED_TRC20_TRANSACTION] is only allowed" - + " to be 1 or 0", e.getMessage()); - } + ContractValidateException e25 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_SHIELDED_TRC20_TRANSACTION + .getCode(), 2)); + Assert.assertEquals("This value[ALLOW_SHIELDED_TRC20_TRANSACTION] is only allowed" + + " to be 1 or 0", e25.getMessage()); hardForkTime = ((ForkBlockVersionEnum.VERSION_4_3.getHardForkTime() - 1) / maintenanceTimeInterval + 1) @@ -325,33 +247,24 @@ public void validateCheck() { .saveLatestBlockHeaderTimestamp(hardForkTime + 1); forkUtils.getManager().getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionEnum.VERSION_4_3.getValue(), stats); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.FREE_NET_LIMIT - .getCode(), -1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals("Bad chain parameter value, valid range is [0,100_000]", - e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.TOTAL_NET_LIMIT.getCode(), -1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals("Bad chain parameter value, valid range is [0, 1_000_000_000_000L]", - e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [ALLOW_OLD_REWARD_OPT]", - e.getMessage()); - } + ContractValidateException e26 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.FREE_NET_LIMIT + .getCode(), -1)); + Assert.assertEquals("Bad chain parameter value, valid range is [0,100_000]", + e26.getMessage()); + + ContractValidateException e27 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.TOTAL_NET_LIMIT.getCode(), -1)); + Assert.assertEquals("Bad chain parameter value, valid range is [0, 1_000_000_000_000L]", + e27.getMessage()); + + ContractValidateException e28 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 2)); + Assert.assertEquals( + "Bad chain parameter id [ALLOW_OLD_REWARD_OPT]", + e28.getMessage()); hardForkTime = ((ForkBlockVersionEnum.VERSION_4_7_4.getHardForkTime() - 1) / maintenanceTimeInterval + 1) * maintenanceTimeInterval; @@ -359,47 +272,35 @@ public void validateCheck() { .saveLatestBlockHeaderTimestamp(hardForkTime + 1); forkUtils.getManager().getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionEnum.VERSION_4_7_4.getValue(), stats); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_OLD_REWARD_OPT] is only allowed to be 1", - e.getMessage()); - } - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_NEW_REWARD] or [ALLOW_TVM_VOTE] proposal must be approved " - + "before [ALLOW_OLD_REWARD_OPT] can be proposed", - e.getMessage()); - } + ContractValidateException e29 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_OLD_REWARD_OPT] is only allowed to be 1", + e29.getMessage()); + ContractValidateException e30 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_NEW_REWARD] or [ALLOW_TVM_VOTE] proposal must be approved " + + "before [ALLOW_OLD_REWARD_OPT] can be proposed", + e30.getMessage()); dynamicPropertiesStore.put("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes(), new BytesCapsule(ByteArray.fromLong(4000))); dynamicPropertiesStore.saveAllowOldRewardOpt(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_OLD_REWARD_OPT] has been valid, no need to propose again", - e.getMessage()); - } - - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_STRICT_MATH.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [ALLOW_STRICT_MATH]", - e.getMessage()); - } + ContractValidateException e31 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_OLD_REWARD_OPT] has been valid, no need to propose again", + e31.getMessage()); + + ContractValidateException e32 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 2)); + Assert.assertEquals( + "Bad chain parameter id [ALLOW_STRICT_MATH]", + e32.getMessage()); hardForkTime = ((ForkBlockVersionEnum.VERSION_4_7_7.getHardForkTime() - 1) / maintenanceTimeInterval + 1) * maintenanceTimeInterval; @@ -407,15 +308,12 @@ public void validateCheck() { .saveLatestBlockHeaderTimestamp(hardForkTime + 1); forkUtils.getManager().getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionEnum.VERSION_4_7_7.getValue(), stats); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_STRICT_MATH.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_STRICT_MATH] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e33 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_STRICT_MATH] is only allowed to be 1", + e33.getMessage()); try { ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_STRICT_MATH.getCode(), 1); @@ -426,15 +324,12 @@ public void validateCheck() { ProposalType.ALLOW_STRICT_MATH.getCode(), 1).build(); ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); ProposalService.process(dbManager, proposalCapsule); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_STRICT_MATH.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_STRICT_MATH] has been valid, no need to propose again", - e.getMessage()); - } + ContractValidateException e34 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_STRICT_MATH] has been valid, no need to propose again", + e34.getMessage()); testEnergyAdjustmentProposal(); @@ -455,15 +350,12 @@ public void validateCheck() { private void testEnergyAdjustmentProposal() { // Should fail because cannot pass the fork controller check - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [ALLOW_ENERGY_ADJUSTMENT]", - e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1)); + Assert.assertEquals( + "Bad chain parameter id [ALLOW_ENERGY_ADJUSTMENT]", + e1.getMessage()); long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() .getMaintenanceTimeInterval(); @@ -480,15 +372,12 @@ private void testEnergyAdjustmentProposal() { .statsByVersion(ForkBlockVersionEnum.VERSION_4_7_5.getValue(), stats); // Should fail because the proposal value is invalid - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_ENERGY_ADJUSTMENT] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e2 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_ENERGY_ADJUSTMENT] is only allowed to be 1", + e2.getMessage()); // Should succeed try { @@ -504,27 +393,21 @@ private void testEnergyAdjustmentProposal() { proposalCapsule.setParameters(parameter); ProposalService.process(dbManager, proposalCapsule); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_ENERGY_ADJUSTMENT] has been valid, no need to propose again", - e.getMessage()); - } + ContractValidateException e3 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_ENERGY_ADJUSTMENT] has been valid, no need to propose again", + e3.getMessage()); } private void testConsensusLogicOptimizationProposal() { - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [CONSENSUS_LOGIC_OPTIMIZATION]", - e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 1)); + Assert.assertEquals( + "Bad chain parameter id [CONSENSUS_LOGIC_OPTIMIZATION]", + e1.getMessage()); long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() .getMaintenanceTimeInterval(); @@ -541,26 +424,20 @@ private void testConsensusLogicOptimizationProposal() { .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); // Should fail because the proposal value is invalid - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[CONSENSUS_LOGIC_OPTIMIZATION] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e2 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 2)); + Assert.assertEquals( + "This value[CONSENSUS_LOGIC_OPTIMIZATION] is only allowed to be 1", + e2.getMessage()); dynamicPropertiesStore.saveConsensusLogicOptimization(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[CONSENSUS_LOGIC_OPTIMIZATION] has been valid, no need to propose again", - e.getMessage()); - } + ContractValidateException e3 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 1)); + Assert.assertEquals( + "[CONSENSUS_LOGIC_OPTIMIZATION] has been valid, no need to propose again", + e3.getMessage()); } @@ -568,15 +445,12 @@ private void testAllowTvmCancunProposal() { byte[] stats = new byte[27]; forkUtils.getManager().getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_CANCUN.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [ALLOW_TVM_CANCUN]", - e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_CANCUN.getCode(), 1)); + Assert.assertEquals( + "Bad chain parameter id [ALLOW_TVM_CANCUN]", + e1.getMessage()); long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() .getMaintenanceTimeInterval(); @@ -593,26 +467,20 @@ private void testAllowTvmCancunProposal() { .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); // Should fail because the proposal value is invalid - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_CANCUN.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_TVM_CANCUN] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e2 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_CANCUN.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_TVM_CANCUN] is only allowed to be 1", + e2.getMessage()); dynamicPropertiesStore.saveAllowTvmCancun(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_CANCUN.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_TVM_CANCUN] has been valid, no need to propose again", - e.getMessage()); - } + ContractValidateException e3 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_CANCUN.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_TVM_CANCUN] has been valid, no need to propose again", + e3.getMessage()); } @@ -620,15 +488,12 @@ private void testAllowTvmBlobProposal() { byte[] stats = new byte[27]; forkUtils.getManager().getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_BLOB.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [ALLOW_TVM_BLOB]", - e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_BLOB.getCode(), 1)); + Assert.assertEquals( + "Bad chain parameter id [ALLOW_TVM_BLOB]", + e1.getMessage()); long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() .getMaintenanceTimeInterval(); @@ -645,26 +510,20 @@ private void testAllowTvmBlobProposal() { .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); // Should fail because the proposal value is invalid - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_BLOB.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_TVM_BLOB] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e2 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_BLOB.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_TVM_BLOB] is only allowed to be 1", + e2.getMessage()); dynamicPropertiesStore.saveAllowTvmBlob(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_BLOB.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_TVM_BLOB] has been valid, no need to propose again", - e.getMessage()); - } + ContractValidateException e3 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_BLOB.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_TVM_BLOB] has been valid, no need to propose again", + e3.getMessage()); } @@ -672,15 +531,12 @@ private void testAllowTvmSelfdestructRestrictionProposal() { byte[] stats = new byte[27]; forkUtils.getManager().getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_1.getValue(), stats); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_SELFDESTRUCT_RESTRICTION.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "Bad chain parameter id [ALLOW_TVM_SELFDESTRUCT_RESTRICTION]", - e.getMessage()); - } + ContractValidateException e1 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_SELFDESTRUCT_RESTRICTION.getCode(), 1)); + Assert.assertEquals( + "Bad chain parameter id [ALLOW_TVM_SELFDESTRUCT_RESTRICTION]", + e1.getMessage()); long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() .getMaintenanceTimeInterval(); @@ -697,26 +553,20 @@ private void testAllowTvmSelfdestructRestrictionProposal() { .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_1.getValue(), stats); // Should fail because the proposal value is invalid - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_SELFDESTRUCT_RESTRICTION.getCode(), 2); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "This value[ALLOW_TVM_SELFDESTRUCT_RESTRICTION] is only allowed to be 1", - e.getMessage()); - } + ContractValidateException e2 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_SELFDESTRUCT_RESTRICTION.getCode(), 2)); + Assert.assertEquals( + "This value[ALLOW_TVM_SELFDESTRUCT_RESTRICTION] is only allowed to be 1", + e2.getMessage()); dynamicPropertiesStore.saveAllowTvmSelfdestructRestriction(1); - try { - ProposalUtil.validator(dynamicPropertiesStore, forkUtils, - ProposalType.ALLOW_TVM_SELFDESTRUCT_RESTRICTION.getCode(), 1); - Assert.fail(); - } catch (ContractValidateException e) { - Assert.assertEquals( - "[ALLOW_TVM_SELFDESTRUCT_RESTRICTION] has been valid, no need to propose again", - e.getMessage()); - } + ContractValidateException e3 = Assert.assertThrows(ContractValidateException.class, + () -> ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_SELFDESTRUCT_RESTRICTION.getCode(), 1)); + Assert.assertEquals( + "[ALLOW_TVM_SELFDESTRUCT_RESTRICTION] has been valid, no need to propose again", + e3.getMessage()); } private void testAllowMarketTransaction() { diff --git a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java index df84433726e..88e95f9653e 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java @@ -101,12 +101,9 @@ private static int getRank(int num) { */ public void test0HashNum() { List hashList = getHash(0); //Empty list. - try { - MerkleTree.getInstance().createTree(hashList); - Assert.assertFalse(true); - } catch (Exception e) { - Assert.assertTrue(e instanceof IndexOutOfBoundsException); - } + Exception e = Assert.assertThrows(Exception.class, + () -> MerkleTree.getInstance().createTree(hashList)); + Assert.assertTrue(e instanceof IndexOutOfBoundsException); } @Test diff --git a/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java b/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java index 500e7454dbe..9c2e8550634 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java @@ -69,12 +69,8 @@ public void testToBytes() Assert.assertArrayEquals(kBytes, lBytes); char c = 'a'; - try { - method.invoke(RLP.class, c); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } + Assert.assertThrows(Exception.class, + () -> method.invoke(RLP.class, c)); } @Test diff --git a/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java index 88734945687..41fdc2e3925 100644 --- a/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java @@ -84,11 +84,7 @@ private long createAsset(String tokenName) { AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); chainBaseManager.getAssetIssueV2Store() .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - try { - ownerCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), TOTAL_SUPPLY); - } catch (Exception e) { - e.printStackTrace(); - } + ownerCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), TOTAL_SUPPLY); accountStore.put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); return id; } diff --git a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java index a908d5d3cea..2fae33870cb 100755 --- a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java @@ -77,12 +77,9 @@ public void setAccountTest() throws Exception { field.set(AccountStore.class, new HashMap<>()); Config config = mock(Config.class); Mockito.when(config.getObjectList("genesis.block.assets")).thenReturn(new ArrayList<>()); - try { - AccountStore.setAccount(config); - Assert.fail(); - } catch (Throwable e) { - Assert.assertTrue(e instanceof TronError); - } + Throwable e = Assert.assertThrows(Throwable.class, + () -> AccountStore.setAccount(config)); + Assert.assertTrue(e instanceof TronError); } @Test diff --git a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java index 1868eae4cba..fd408281ab2 100644 --- a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java @@ -46,7 +46,7 @@ public void testPut() { Assert.assertNotNull(blockCapsule1); Assert.assertEquals(number, blockCapsule1.getNum()); } catch (ItemNotFoundException | BadItemException e) { - e.printStackTrace(); + Assert.fail(e.getMessage()); } } @@ -63,7 +63,7 @@ public void testGet() { Assert.assertEquals(number, blockCapsule1.getNum()); } catch (ItemNotFoundException | BadItemException e) { - e.printStackTrace(); + Assert.fail(e.getMessage()); } } @@ -83,7 +83,7 @@ public void testDelete() { BlockCapsule blockCapsule2 = blockStore.getUnchecked(blockId); Assert.assertNull(blockCapsule2); } catch (ItemNotFoundException | BadItemException e) { - e.printStackTrace(); + Assert.fail(e.getMessage()); } } diff --git a/framework/src/test/java/org/tron/core/db/DBIteratorTest.java b/framework/src/test/java/org/tron/core/db/DBIteratorTest.java index 58923ce50b6..0966d904093 100644 --- a/framework/src/test/java/org/tron/core/db/DBIteratorTest.java +++ b/framework/src/test/java/org/tron/core/db/DBIteratorTest.java @@ -86,43 +86,36 @@ public void testRocksDb() throws RocksDBException, IOException { RocksDB db = RocksDB.open(options, file.toString())) { db.put("1".getBytes(StandardCharsets.UTF_8), "1".getBytes(StandardCharsets.UTF_8)); db.put("2".getBytes(StandardCharsets.UTF_8), "2".getBytes(StandardCharsets.UTF_8)); - RockStoreIterator iterator = new RockStoreIterator(db.newIterator(), new ReadOptions()); - iterator.seekToFirst(); - Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.getKey()); - Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.next().getValue()); - Assert.assertTrue(iterator.hasNext()); - - Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); - Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.next().getKey()); - Assert.assertFalse(iterator.hasNext()); - - try { - iterator.seekToLast(); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalStateException); + try (RockStoreIterator iterator = + new RockStoreIterator(db.newIterator(), new ReadOptions())) { + iterator.seekToFirst(); + Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.getKey()); + Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.next().getValue()); + Assert.assertTrue(iterator.hasNext()); + + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.next().getKey()); + Assert.assertFalse(iterator.hasNext()); + + Assert.assertThrows(IllegalStateException.class, iterator::seekToLast); } - iterator = new RockStoreIterator(db.newIterator(), new ReadOptions()); - iterator.seekToLast(); - Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getKey()); - Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); - iterator.seekToFirst(); - while (iterator.hasNext()) { + try ( + RockStoreIterator iterator = + new RockStoreIterator(db.newIterator(), new ReadOptions())) { + iterator.seekToLast(); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getKey()); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); + iterator.seekToFirst(); + while (iterator.hasNext()) { + iterator.next(); + } + Assert.assertFalse(iterator.hasNext()); + Assert.assertThrows(IllegalStateException.class, iterator::getKey); + Assert.assertThrows(IllegalStateException.class, iterator::getValue); + thrown.expect(NoSuchElementException.class); iterator.next(); } - Assert.assertFalse(iterator.hasNext()); - try { - iterator.getKey(); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalStateException); - } - try { - iterator.getValue(); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalStateException); - } - thrown.expect(NoSuchElementException.class); - iterator.next(); } } diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index b9808b89193..a07fb291f34 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -272,12 +272,8 @@ public void pushBlock() { } } - try { - chainManager.getBlockIdByNum(-1); - Assert.fail(); - } catch (ItemNotFoundException e) { - Assert.assertTrue(true); - } + Assert.assertThrows(ItemNotFoundException.class, + () -> chainManager.getBlockIdByNum(-1)); try { dbManager.getBlockChainHashesOnFork(blockCapsule2.getBlockId()); } catch (Exception e) { @@ -1185,14 +1181,8 @@ public void testExpireTransaction() { TransactionCapsule trx = new TransactionCapsule(tc, ContractType.TransferContract); long latestBlockTime = dbManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); trx.setExpiration(latestBlockTime - 100); - try { - dbManager.validateCommon(trx); - Assert.fail(); - } catch (TransactionExpirationException e) { - Assert.assertTrue(true); - } catch (TooBigTransactionException e) { - Assert.fail(); - } + Assert.assertThrows(TransactionExpirationException.class, + () -> dbManager.validateCommon(trx)); } @Test diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java index 76e9a18e31a..4948f3d935c 100644 --- a/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java +++ b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java @@ -172,9 +172,8 @@ private SnapshotImpl getSnapshotImplIns(Snapshot snapshot) { constructor.setAccessible(true); return (SnapshotImpl) constructor.newInstance(snapshot); } catch (Exception e) { - e.printStackTrace(); + throw new AssertionError(e); } - return null; } } diff --git a/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java b/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java index 82c887fad53..6c0b8733a18 100644 --- a/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java +++ b/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java @@ -20,21 +20,15 @@ public void test() throws Exception { be1.setBlockId(b1); be1.setParentId(b1); be1.setSolidId(b1); - try { - BlockEventCache.add(be1); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(e instanceof EventException); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> BlockEventCache.add(be1)); + Assert.assertTrue(e1 instanceof EventException); BlockEventCache.init(new BlockCapsule.BlockId(getBlockId(), 100)); - try { - BlockEventCache.add(be1); - Assert.fail(); - } catch (Exception e) { - Assert.assertTrue(e instanceof EventException); - } + Exception e2 = Assert.assertThrows(Exception.class, + () -> BlockEventCache.add(be1)); + Assert.assertTrue(e2 instanceof EventException); BlockEventCache.init(b1); diff --git a/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java index d1fb95f2f69..227e539aa37 100644 --- a/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java +++ b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java @@ -34,7 +34,6 @@ import org.tron.core.ChainBaseManager; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.capsule.TransactionRetCapsule; import org.tron.core.capsule.WitnessCapsule; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @@ -45,7 +44,7 @@ import org.tron.core.services.event.BlockEventGet; import org.tron.core.services.event.bo.BlockEvent; import org.tron.core.store.DynamicPropertiesStore; -import org.tron.core.store.TransactionRetStore; +import org.tron.core.vm.config.ConfigLoader; import org.tron.protos.Protocol; @Slf4j @@ -69,8 +68,8 @@ public class BlockEventGetTest extends BlockGenerate { static LocalDateTime localDateTime = LocalDateTime.now(); - private long time = ZonedDateTime.of(localDateTime, - ZoneId.systemDefault()).toInstant().toEpochMilli(); + private long time = + ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli(); public static String dbPath() { @@ -99,18 +98,21 @@ public void before() throws IOException { chainManager = dbManager.getChainBaseManager(); tronNetDelegate = context.getBean(TronNetDelegate.class); tronNetDelegate.setExit(false); - currentHeader = dbManager.getDynamicPropertiesStore() - .getLatestBlockHeaderNumberFromDB(); + currentHeader = dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumberFromDB(); ByteString addressBS = ByteString.copyFrom(address); WitnessCapsule witnessCapsule = new WitnessCapsule(addressBS); chainManager.getWitnessStore().put(address, witnessCapsule); chainManager.addWitness(addressBS); - AccountCapsule accountCapsule = new AccountCapsule(Protocol.Account.newBuilder() - .setAddress(addressBS).setBalance((long) 1e10).build()); + AccountCapsule accountCapsule = new AccountCapsule( + Protocol.Account.newBuilder().setAddress(addressBS).setBalance((long) 1e10).build()); chainManager.getAccountStore().put(address, accountCapsule); + // Reset global static flag that other tests may leave as true, which would prevent + // ConfigLoader.load() from updating VMConfig during VMActuator.execute(). + ConfigLoader.disable = false; + DynamicPropertiesStore dps = dbManager.getDynamicPropertiesStore(); dps.saveAllowTvmTransferTrc10(1); dps.saveAllowTvmConstantinople(1); @@ -129,8 +131,8 @@ public void test() throws Exception { Manager manager = context.getBean(Manager.class); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); - ChainBaseManager.getChainBaseManager() - .getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); + ChainBaseManager.getChainBaseManager().getWitnessScheduleStore() + .saveActiveWitnesses(new ArrayList<>()); ChainBaseManager.getChainBaseManager().addWitness(ByteString.copyFrom(address)); String code = "608060405234801561000f575f80fd5b50d3801561001b575f80fd5b50d28015610027575f" @@ -141,15 +143,16 @@ public void test() throws Exception { + "00a0565b9050919050565b6100dc816100b2565b82525050565b5f6020820190506100f55f83018461" + "00d3565b92915050565b603e806101075f395ff3fe60806040525f80fdfea26474726f6e582212200c" + "57c973388f044038eff0e6474425b38037e75e66d6b3047647290605449c7764736f6c63430008140033"; - Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - "TestTRC20", address, "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\"" - + ":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\"" - + ":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\"" - + ":\"Transfer\",\"type\":\"event\"}]", code, 0, (long) 1e9, 100, null, 1); - trx = trx.toBuilder().addRet( - Protocol.Transaction.Result.newBuilder() - .setContractRetValue(Protocol.Transaction.Result.contractResult.SUCCESS_VALUE) - .build()).build(); + Protocol.Transaction trx = + TvmTestUtils.generateDeploySmartContractAndGetTransaction("TestTRC20", address, + "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\"" + + ":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\"" + + ":\"address\"},{\"indexed\":false,\"name\":\"value\"," + + "\"type\":\"uint256\"}],\"name\"" + + ":\"Transfer\",\"type\":\"event\"}]", code, 0, (long) 1e9, 100, null, 1); + trx = trx.toBuilder().addRet(Protocol.Transaction.Result.newBuilder() + .setContractRetValue(Protocol.Transaction.Result.contractResult.SUCCESS_VALUE).build()) + .build(); Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); BlockCapsule blockCapsule = new BlockCapsule(block.toBuilder().addTransactions(trx).build()); @@ -163,8 +166,7 @@ public void test() throws Exception { // Set energy price history to test boundary cases manager.getDynamicPropertiesStore().saveEnergyPriceHistory( - manager.getDynamicPropertiesStore().getEnergyPriceHistory() - + "," + time + ":210"); + manager.getDynamicPropertiesStore().getEnergyPriceHistory() + "," + time + ":210"); EventPluginConfig config = new EventPluginConfig(); config.setSendQueueLength(1000); @@ -207,8 +209,9 @@ public void test() throws Exception { // Here energy unit price should be 100 not 210, // cause block time is equal to 210`s effective time - Assert.assertEquals(100, blockEvent.getTransactionLogTriggerCapsules() - .get(0).getTransactionLogTrigger().getEnergyUnitPrice()); + Assert.assertEquals(100, + blockEvent.getTransactionLogTriggerCapsules().get(0).getTransactionLogTrigger() + .getEnergyUnitPrice()); } catch (Exception e) { Assert.fail(); } @@ -217,8 +220,8 @@ public void test() throws Exception { @Test public void getTransactionTriggers() throws Exception { BlockEventGet blockEventGet = new BlockEventGet(); - BlockCapsule bc = new BlockCapsule(1, Sha256Hash.ZERO_HASH, - 100, Sha256Hash.ZERO_HASH.getByteString()); + BlockCapsule bc = + new BlockCapsule(1, Sha256Hash.ZERO_HASH, 100, Sha256Hash.ZERO_HASH.getByteString()); List list = blockEventGet.getTransactionTriggers(bc, 1); Assert.assertEquals(0, list.size()); @@ -237,7 +240,7 @@ public void getTransactionTriggers() throws Exception { Manager manager = mock(Manager.class); ReflectUtils.setFieldValue(blockEventGet, "manager", manager); Mockito.when(manager.getTransactionInfoByBlockNum(1)) - .thenReturn(GrpcAPI.TransactionInfoList.newBuilder().build()); + .thenReturn(GrpcAPI.TransactionInfoList.newBuilder().build()); list = blockEventGet.getTransactionTriggers(bc, 1); Assert.assertEquals(1, list.size()); @@ -254,8 +257,7 @@ public void getTransactionTriggers() throws Exception { resourceBuild.setNetUsage(6); String address = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; - infoBuild - .setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(address))) + infoBuild.setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(address))) .addContractResult(ByteString.copyFrom(ByteArray.fromHexString("112233"))) .setReceipt(resourceBuild.build()); @@ -263,14 +265,12 @@ public void getTransactionTriggers() throws Exception { Mockito.when(manager.getChainBaseManager()).thenReturn(chainBaseManager); - GrpcAPI.TransactionInfoList result = GrpcAPI.TransactionInfoList.newBuilder() - .addTransactionInfo(infoBuild.build()).build(); + GrpcAPI.TransactionInfoList result = + GrpcAPI.TransactionInfoList.newBuilder().addTransactionInfo(infoBuild.build()).build(); - Mockito.when(manager.getTransactionInfoByBlockNum(0)) - .thenReturn(result); + Mockito.when(manager.getTransactionInfoByBlockNum(0)).thenReturn(result); - Protocol.Block block = Protocol.Block.newBuilder() - .addTransactions(transaction).build(); + Protocol.Block block = Protocol.Block.newBuilder().addTransactions(transaction).build(); BlockCapsule blockCapsule = new BlockCapsule(block); blockCapsule.getTransactions().forEach(t -> t.setBlockNum(blockCapsule.getNum())); @@ -278,23 +278,17 @@ public void getTransactionTriggers() throws Exception { list = blockEventGet.getTransactionTriggers(blockCapsule, 1); Assert.assertEquals(1, list.size()); - Assert.assertEquals(1, - list.get(0).getTransactionLogTrigger().getLatestSolidifiedBlockNumber()); - Assert.assertEquals(0, - list.get(0).getTransactionLogTrigger().getBlockNumber()); - Assert.assertEquals(2, - list.get(0).getTransactionLogTrigger().getEnergyUsageTotal()); + Assert.assertEquals(1, list.get(0).getTransactionLogTrigger().getLatestSolidifiedBlockNumber()); + Assert.assertEquals(0, list.get(0).getTransactionLogTrigger().getBlockNumber()); + Assert.assertEquals(2, list.get(0).getTransactionLogTrigger().getEnergyUsageTotal()); Mockito.when(manager.getTransactionInfoByBlockNum(0)) .thenReturn(GrpcAPI.TransactionInfoList.newBuilder().build()); list = blockEventGet.getTransactionTriggers(blockCapsule, 1); Assert.assertEquals(1, list.size()); - Assert.assertEquals(1, - list.get(0).getTransactionLogTrigger().getLatestSolidifiedBlockNumber()); - Assert.assertEquals(0, - list.get(0).getTransactionLogTrigger().getBlockNumber()); - Assert.assertEquals(0, - list.get(0).getTransactionLogTrigger().getEnergyUsageTotal()); + Assert.assertEquals(1, list.get(0).getTransactionLogTrigger().getLatestSolidifiedBlockNumber()); + Assert.assertEquals(0, list.get(0).getTransactionLogTrigger().getBlockNumber()); + Assert.assertEquals(0, list.get(0).getTransactionLogTrigger().getEnergyUsageTotal()); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java index abb73671161..07eb6d7da1f 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java @@ -7,9 +7,13 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.logsfilter.capsule.BlockFilterCapsule; import org.tron.common.utils.ByteArray; import org.tron.core.exception.ItemNotFoundException; @@ -18,6 +22,7 @@ @Slf4j public class ConcurrentHashMapTest { + private static final String EXECUTOR_NAME = "jsonrpc-concurrent-map-test"; private static int randomInt(int minInt, int maxInt) { return (int) round(random(true) * (maxInt - minInt) + minInt, true); @@ -52,12 +57,14 @@ public void testHandleBlockHash() { try { Thread.sleep(200); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + Assert.fail("Interrupted during test setup: " + e.getMessage()); } - Thread putThread = new Thread(new Runnable() { - public void run() { + ExecutorService executor = ExecutorServiceManager.newFixedThreadPool(EXECUTOR_NAME, 4); + try { + Future putTask = executor.submit(() -> { for (int i = 1; i <= times; i++) { logger.info("put time {}, from {} to {}", i, (1 + (i - 1) * eachCount), i * eachCount); @@ -69,21 +76,20 @@ public void run() { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + throw new AssertionError("putThread interrupted", e); } } - } - - }); + }); - Thread getThread1 = new Thread(new Runnable() { - public void run() { + Future getTask1 = executor.submit(() -> { for (int t = 1; t <= times * 2; t++) { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + throw new AssertionError("getThread1 interrupted", e); } logger.info("Thread1 get time {}", t); @@ -98,22 +104,20 @@ public void run() { } } catch (ItemNotFoundException e) { - e.printStackTrace(); - // Assert.fail(e.getMessage()); + Assert.fail("Filter ID should always exist: " + e.getMessage()); } } } - } - }); + }); - Thread getThread2 = new Thread(new Runnable() { - public void run() { + Future getTask2 = executor.submit(() -> { for (int t = 1; t <= times * 2; t++) { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + throw new AssertionError("getThread2 interrupted", e); } logger.info("Thread2 get time {}", t); @@ -132,21 +136,20 @@ public void run() { } } catch (ItemNotFoundException e) { - // Assert.fail(e.getMessage()); + Assert.fail("Filter ID should always exist: " + e.getMessage()); } } } - } - }); + }); - Thread getThread3 = new Thread(new Runnable() { - public void run() { + Future getTask3 = executor.submit(() -> { for (int t = 1; t <= times * 2; t++) { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + throw new AssertionError("getThread3 interrupted", e); } logger.info("Thread3 get time {}", t); @@ -160,31 +163,30 @@ public void run() { try { resultMap3.get(String.valueOf(k)).add(str.toString()); } catch (Exception e) { - logger.error("resultMap3 get {} exception {}", k, e.getMessage()); - e.printStackTrace(); + throw new AssertionError("resultMap3 get " + k + " exception", e); } } } catch (ItemNotFoundException e) { - // Assert.fail(e.getMessage()); + Assert.fail("Filter ID should always exist: " + e.getMessage()); } } } + }); + + for (Future future : new Future[] {putTask, getTask1, getTask2, getTask3}) { + try { + future.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + Assert.fail("Main thread interrupted while waiting for worker threads: " + + e.getMessage()); + } catch (ExecutionException e) { + Assert.fail("Worker thread failed: " + e.getCause()); + } } - }); - - putThread.start(); - getThread1.start(); - getThread2.start(); - getThread3.start(); - - try { - putThread.join(); - getThread1.join(); - getThread2.join(); - getThread3.join(); - } catch (InterruptedException e) { - e.printStackTrace(); + } finally { + ExecutorServiceManager.shutdownAndAwaitTermination(executor, EXECUTOR_NAME); } logger.info("-----------------------------------------------------------------------"); @@ -205,4 +207,4 @@ public void run() { } } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java index ced7048c9d2..e1a698216c4 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java @@ -345,20 +345,14 @@ public void testGetBlockByNumber() { Assert.assertEquals(ByteArray.toJsonHex(blockCapsule2.getNum()), blockResult.getNumber()); // pending - try { - tronJsonRpc.ethGetBlockByNumber("pending", false); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG pending not supported", e.getMessage()); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.ethGetBlockByNumber("pending", false)); + Assert.assertEquals("TAG pending not supported", e1.getMessage()); // invalid - try { - tronJsonRpc.ethGetBlockByNumber("0x", false); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("invalid block number", e.getMessage()); - } + Exception e2 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.ethGetBlockByNumber("0x", false)); + Assert.assertEquals("invalid block number", e2.getMessage()); } @Test @@ -432,12 +426,9 @@ public void testServicesInit() { public void testGetByJsonBlockId() { long blkNum = 0; - try { - getByJsonBlockId("pending", wallet); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG pending not supported", e.getMessage()); - } + Exception pendingEx = Assert.assertThrows(Exception.class, + () -> getByJsonBlockId("pending", wallet)); + Assert.assertEquals("TAG pending not supported", pendingEx.getMessage()); try { blkNum = getByJsonBlockId(null, wallet); @@ -467,49 +458,34 @@ public void testGetByJsonBlockId() { } Assert.assertEquals(10L, blkNum); - try { - getByJsonBlockId("abc", wallet); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("Incorrect hex syntax", e.getMessage()); - } + Exception abcEx = Assert.assertThrows(Exception.class, + () -> getByJsonBlockId("abc", wallet)); + Assert.assertEquals("Incorrect hex syntax", abcEx.getMessage()); - try { - getByJsonBlockId("0xxabc", wallet); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - // https://bugs.openjdk.org/browse/JDK-8176425, from JDK 12, the exception message is changed - Assert.assertTrue(e.getMessage().startsWith("For input string: \"xabc\"")); - } + Exception hexEx = Assert.assertThrows(Exception.class, + () -> getByJsonBlockId("0xxabc", wallet)); + // https://bugs.openjdk.org/browse/JDK-8176425, from JDK 12, the exception message is changed + Assert.assertTrue(hexEx.getMessage().startsWith("For input string: \"xabc\"")); } @Test public void testGetTrxBalance() { String balance = ""; - try { - tronJsonRpc.getTrxBalance("", "earliest"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getTrxBalance("", "earliest")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e1.getMessage()); - try { - tronJsonRpc.getTrxBalance("", "pending"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } + Exception e2 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getTrxBalance("", "pending")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e2.getMessage()); - try { - tronJsonRpc.getTrxBalance("", "finalized"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } + Exception e3 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getTrxBalance("", "finalized")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e3.getMessage()); try { balance = tronJsonRpc.getTrxBalance("0xabd4b9367799eaa3197fecb144eb71de1e049abc", @@ -522,83 +498,56 @@ public void testGetTrxBalance() { @Test public void testGetStorageAt() { - try { - tronJsonRpc.getStorageAt("", "", "earliest"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } - - try { - tronJsonRpc.getStorageAt("", "", "pending"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } - - try { - tronJsonRpc.getStorageAt("", "", "finalized"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getStorageAt("", "", "earliest")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e1.getMessage()); + + Exception e2 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getStorageAt("", "", "pending")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e2.getMessage()); + + Exception e3 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getStorageAt("", "", "finalized")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e3.getMessage()); } @Test public void testGetABIOfSmartContract() { - try { - tronJsonRpc.getABIOfSmartContract("", "earliest"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } - - try { - tronJsonRpc.getABIOfSmartContract("", "pending"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } - - try { - tronJsonRpc.getABIOfSmartContract("", "finalized"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getABIOfSmartContract("", "earliest")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e1.getMessage()); + + Exception e2 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getABIOfSmartContract("", "pending")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e2.getMessage()); + + Exception e3 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getABIOfSmartContract("", "finalized")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e3.getMessage()); } @Test public void testGetCall() { - try { - tronJsonRpc.getCall(null, "earliest"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } - - try { - tronJsonRpc.getCall(null, "pending"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } - - try { - tronJsonRpc.getCall(null, "finalized"); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("TAG [earliest | pending | finalized] not supported", - e.getMessage()); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getCall(null, "earliest")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e1.getMessage()); + + Exception e2 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getCall(null, "pending")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e2.getMessage()); + + Exception e3 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getCall(null, "finalized")); + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e3.getMessage()); } /** @@ -666,13 +615,11 @@ public void testLogFilterWrapper() { } catch (JsonRpcInvalidParamsException e) { Assert.fail(); } - try { - new LogFilterWrapper(new FilterRequest("0x78", "0x14", - null, null, null), 100, null, false); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals("please verify: fromBlock <= toBlock", e.getMessage()); - } + JsonRpcInvalidParamsException fromToEx = + Assert.assertThrows(JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("0x78", "0x14", + null, null, null), 100, null, false)); + Assert.assertEquals("please verify: fromBlock <= toBlock", fromToEx.getMessage()); //fromBlock or toBlock is not hex num try { @@ -691,13 +638,11 @@ public void testLogFilterWrapper() { } catch (JsonRpcInvalidParamsException e) { Assert.fail(); } - try { - new LogFilterWrapper(new FilterRequest("pending", null, null, null, null), - 100, null, false); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals("TAG pending not supported", e.getMessage()); - } + JsonRpcInvalidParamsException pendingFilterEx = Assert.assertThrows( + JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("pending", null, null, null, null), + 100, null, false)); + Assert.assertEquals("TAG pending not supported", pendingFilterEx.getMessage()); try { LogFilterWrapper logFilterWrapper = new LogFilterWrapper(new FilterRequest("finalized", null, null, null, null), 100, wallet, false); @@ -706,13 +651,11 @@ public void testLogFilterWrapper() { } catch (JsonRpcInvalidParamsException e) { Assert.fail(); } - try { - new LogFilterWrapper(new FilterRequest("test", null, null, null, null), - 100, null, false); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals("Incorrect hex syntax", e.getMessage()); - } + JsonRpcInvalidParamsException testSyntaxEx = Assert.assertThrows( + JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("test", null, null, null, null), + 100, null, false)); + Assert.assertEquals("Incorrect hex syntax", testSyntaxEx.getMessage()); // to = 8000 try { @@ -722,15 +665,13 @@ public void testLogFilterWrapper() { Assert.fail(); } - try { - new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, - null, null), LATEST_BLOCK_NUM, null, true); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals( - "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, - e.getMessage()); - } + JsonRpcInvalidParamsException rangeEx1 = Assert.assertThrows( + JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, true)); + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + rangeEx1.getMessage()); try { new LogFilterWrapper(new FilterRequest("0x0", "latest", null, @@ -739,15 +680,13 @@ public void testLogFilterWrapper() { Assert.fail(); } - try { - new LogFilterWrapper(new FilterRequest("0x0", "latest", null, - null, null), LATEST_BLOCK_NUM, null, true); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals( - "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, - e.getMessage()); - } + JsonRpcInvalidParamsException rangeEx2 = Assert.assertThrows( + JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("0x0", "latest", null, + null, null), LATEST_BLOCK_NUM, null, true)); + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + rangeEx2.getMessage()); // from = 100, current = 5_000, to = Long.MAX_VALUE try { @@ -764,15 +703,13 @@ public void testLogFilterWrapper() { } // from = 100 - try { - new LogFilterWrapper(new FilterRequest("0x64", "latest", null, - null, null), LATEST_BLOCK_NUM, null, true); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals( - "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, - e.getMessage()); - } + JsonRpcInvalidParamsException rangeEx3 = Assert.assertThrows( + JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("0x64", "latest", null, + null, null), LATEST_BLOCK_NUM, null, true)); + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + rangeEx3.getMessage()); try { new LogFilterWrapper(new FilterRequest("0x64", "latest", null, null, null), LATEST_BLOCK_NUM, null, false); @@ -866,15 +803,13 @@ public void testMaxSubTopics() { } topics.add(subTopics); - try { - new LogFilterWrapper(new FilterRequest("0xbb8", "0x1f40", - null, topics.toArray(), null), LATEST_BLOCK_NUM, null, false); - Assert.fail("Expected to be thrown"); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals( - "exceed max topics: " + Args.getInstance().getJsonRpcMaxSubTopics(), - e.getMessage()); - } + JsonRpcInvalidParamsException topicsEx = Assert.assertThrows( + JsonRpcInvalidParamsException.class, + () -> new LogFilterWrapper(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null), LATEST_BLOCK_NUM, null, false)); + Assert.assertEquals( + "exceed max topics: " + Args.getInstance().getJsonRpcMaxSubTopics(), + topicsEx.getMessage()); try { tronJsonRpc.getLogs(new FilterRequest("0xbb8", "0x1f40", @@ -978,40 +913,25 @@ public void testNewFilterFinalizedBlock() { Assert.fail(); } - try { - tronJsonRpc.newFilter(new FilterRequest("finalized", null, null, null, null)); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("invalid block range params", e.getMessage()); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.newFilter(new FilterRequest("finalized", null, null, null, null))); + Assert.assertEquals("invalid block range params", e1.getMessage()); - try { - tronJsonRpc.newFilter(new FilterRequest(null, "finalized", null, null, null)); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("invalid block range params", e.getMessage()); - } + Exception e2 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.newFilter(new FilterRequest(null, "finalized", null, null, null))); + Assert.assertEquals("invalid block range params", e2.getMessage()); - try { - tronJsonRpc.newFilter(new FilterRequest("finalized", "latest", null, null, null)); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("invalid block range params", e.getMessage()); - } + Exception e3 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.newFilter(new FilterRequest("finalized", "latest", null, null, null))); + Assert.assertEquals("invalid block range params", e3.getMessage()); - try { - tronJsonRpc.newFilter(new FilterRequest("0x1", "finalized", null, null, null)); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("invalid block range params", e.getMessage()); - } + Exception e4 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.newFilter(new FilterRequest("0x1", "finalized", null, null, null))); + Assert.assertEquals("invalid block range params", e4.getMessage()); - try { - tronJsonRpc.newFilter(new FilterRequest("finalized", "finalized", null, null, null)); - Assert.fail("Expected to be thrown"); - } catch (Exception e) { - Assert.assertEquals("invalid block range params", e.getMessage()); - } + Exception e5 = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.newFilter(new FilterRequest("finalized", "finalized", null, null, null))); + Assert.assertEquals("invalid block range params", e5.getMessage()); } @Test @@ -1052,19 +972,13 @@ public void testGetBlockReceipts() { throw new RuntimeException(e); } - try { - tronJsonRpc.getBlockReceipts("pending"); - Assert.fail(); - } catch (Exception e) { - Assert.assertEquals(TAG_PENDING_SUPPORT_ERROR, e.getMessage()); - } + Exception pendingReceiptsEx = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getBlockReceipts("pending")); + Assert.assertEquals(TAG_PENDING_SUPPORT_ERROR, pendingReceiptsEx.getMessage()); - try { - tronJsonRpc.getBlockReceipts("test"); - Assert.fail(); - } catch (Exception e) { - Assert.assertEquals("invalid block number", e.getMessage()); - } + Exception testReceiptsEx = Assert.assertThrows(Exception.class, + () -> tronJsonRpc.getBlockReceipts("test")); + Assert.assertEquals("invalid block number", testReceiptsEx.getMessage()); try { List transactionReceiptList = tronJsonRpc.getBlockReceipts("0x2"); diff --git a/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java b/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java index d80d10694a8..94269e86fec 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java @@ -3,7 +3,6 @@ import java.lang.reflect.Method; import java.util.BitSet; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import javax.annotation.Resource; import org.junit.After; import org.junit.Assert; @@ -11,6 +10,7 @@ import org.junit.Test; import org.tron.common.BaseTest; import org.tron.common.TestConstants; +import org.tron.common.es.ExecutorServiceManager; import org.tron.core.config.args.Args; import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; import org.tron.core.services.jsonrpc.filters.LogBlockQuery; @@ -21,6 +21,7 @@ public class LogBlockQueryTest extends BaseTest { @Resource SectionBloomStore sectionBloomStore; + private static final String EXECUTOR_NAME = "log-block-query-test"; private ExecutorService sectionExecutor; private Method partialMatchMethod; private static final long CURRENT_MAX_BLOCK_NUM = 50000L; @@ -31,10 +32,10 @@ public class LogBlockQueryTest extends BaseTest { @Before public void setup() throws Exception { - sectionExecutor = Executors.newFixedThreadPool(5); - + sectionExecutor = ExecutorServiceManager.newFixedThreadPool(EXECUTOR_NAME, 5); + // Get private method through reflection - partialMatchMethod = LogBlockQuery.class.getDeclaredMethod("partialMatch", + partialMatchMethod = LogBlockQuery.class.getDeclaredMethod("partialMatch", int[][].class, int.class); partialMatchMethod.setAccessible(true); @@ -52,9 +53,7 @@ public void setup() throws Exception { @After public void tearDown() { - if (sectionExecutor != null && !sectionExecutor.isShutdown()) { - sectionExecutor.shutdown(); - } + ExecutorServiceManager.shutdownAndAwaitTermination(sectionExecutor, EXECUTOR_NAME); } @Test @@ -63,8 +62,8 @@ public void testPartialMatch() throws Exception { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("0x0", "0x1", null, null, null), CURRENT_MAX_BLOCK_NUM, null, false); - - LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, + + LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, CURRENT_MAX_BLOCK_NUM, sectionExecutor); int section = 0; @@ -105,4 +104,4 @@ public void testPartialMatch() throws Exception { Assert.assertNotNull(result); Assert.assertTrue(result.isEmpty()); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java b/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java index d31f7a4f63d..39bcc30e278 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java @@ -4,12 +4,14 @@ import java.util.BitSet; import java.util.List; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import javax.annotation.Resource; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import org.tron.common.BaseTest; import org.tron.common.TestConstants; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.runtime.vm.DataWord; import org.tron.common.runtime.vm.LogInfo; import org.tron.common.utils.ByteArray; @@ -28,10 +30,22 @@ public class SectionBloomStoreTest extends BaseTest { @Resource SectionBloomStore sectionBloomStore; + private ExecutorService sectionExecutor; + static { Args.setParam(new String[] {"--output-directory", dbPath()}, TestConstants.TEST_CONF); } + @Before + public void setUp() { + sectionExecutor = ExecutorServiceManager.newFixedThreadPool("section-bloom-query", 5); + } + + @After + public void tearDown() { + ExecutorServiceManager.shutdownAndAwaitTermination(sectionExecutor, "section-bloom-query"); + } + @Test public void testPutAndGet() { BitSet bitSet = new BitSet(SectionBloomStore.BLOCK_PER_SECTION); @@ -126,7 +140,6 @@ public void testWriteAndQuery() { } long currentMaxBlockNum = 50000; - ExecutorService sectionExecutor = Executors.newFixedThreadPool(5); //query one address try { @@ -236,6 +249,5 @@ public void testWriteAndQuery() { Assert.fail(); } - sectionExecutor.shutdownNow(); } } diff --git a/framework/src/test/java/org/tron/core/net/MessageTest.java b/framework/src/test/java/org/tron/core/net/MessageTest.java index 5b81d18a599..3757333aa6d 100644 --- a/framework/src/test/java/org/tron/core/net/MessageTest.java +++ b/framework/src/test/java/org/tron/core/net/MessageTest.java @@ -19,29 +19,16 @@ public class MessageTest { private DisconnectMessage disconnectMessage; @Test - public void test1() throws Exception { - byte[] bytes = new DisconnectMessage(ReasonCode.TOO_MANY_PEERS).getData(); + public void test1() { DisconnectMessageTest disconnectMessageTest = new DisconnectMessageTest(); try { disconnectMessage = new DisconnectMessage(MessageTypes.P2P_DISCONNECT.asByte(), disconnectMessageTest.toByteArray()); } catch (Exception e) { - System.out.println(e.getMessage()); Assert.assertTrue(e instanceof P2pException); } } - public void test2() throws Exception { - DisconnectMessageTest disconnectMessageTest = new DisconnectMessageTest(); - long startTime = System.currentTimeMillis(); - for (int i = 0; i < 100000; i++) { - disconnectMessage = new DisconnectMessage(MessageTypes.P2P_DISCONNECT.asByte(), - disconnectMessageTest.toByteArray()); - } - long endTime = System.currentTimeMillis(); - System.out.println("spend time : " + (endTime - startTime)); - } - @Test public void testMessageStatistics() { MessageStatistics messageStatistics = new MessageStatistics(); diff --git a/framework/src/test/java/org/tron/core/net/NodeTest.java b/framework/src/test/java/org/tron/core/net/NodeTest.java index cbf545af646..979c306fd98 100644 --- a/framework/src/test/java/org/tron/core/net/NodeTest.java +++ b/framework/src/test/java/org/tron/core/net/NodeTest.java @@ -28,30 +28,18 @@ public class NodeTest { public void testIpV4() { InetSocketAddress address1 = NetUtil.parseInetSocketAddress("192.168.0.1:18888"); Assert.assertNotNull(address1); - try { - NetUtil.parseInetSocketAddress("192.168.0.1"); - Assert.fail(); - } catch (RuntimeException e) { - Assert.assertTrue(true); - } + Assert.assertThrows(RuntimeException.class, + () -> NetUtil.parseInetSocketAddress("192.168.0.1")); } @Test public void testIpV6() { - try { - NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb:18888"); - Assert.fail(); - } catch (RuntimeException e) { - Assert.assertTrue(true); - } + Assert.assertThrows(RuntimeException.class, + () -> NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb:18888")); InetSocketAddress address2 = NetUtil.parseInetSocketAddress("[fe80::216:3eff:fe0e:23bb]:18888"); Assert.assertNotNull(address2); - try { - NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb"); - Assert.fail(); - } catch (RuntimeException e) { - Assert.assertTrue(true); - } + Assert.assertThrows(RuntimeException.class, + () -> NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb")); } @Test diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java index 270002fffba..e05ee29d015 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java @@ -111,21 +111,17 @@ public void testSyncFetchCheck() { FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler(); - try { - Mockito.when(peer.getLastSyncBlockId()) + Mockito.when(peer.getLastSyncBlockId()) .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1000L)); - fetchInvDataMsgHandler.processMessage(peer, msg); - } catch (Exception e) { - Assert.assertEquals(e.getMessage(), "maxBlockNum: 1000, blockNum: 10000"); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> fetchInvDataMsgHandler.processMessage(peer, msg)); + Assert.assertEquals("maxBlockNum: 1000, blockNum: 10000", e1.getMessage()); - try { - Mockito.when(peer.getLastSyncBlockId()) + Mockito.when(peer.getLastSyncBlockId()) .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 20000L)); - fetchInvDataMsgHandler.processMessage(peer, msg); - } catch (Exception e) { - Assert.assertEquals(e.getMessage(), "minBlockNum: 16000, blockNum: 10000"); - } + Exception e2 = Assert.assertThrows(Exception.class, + () -> fetchInvDataMsgHandler.processMessage(peer, msg)); + Assert.assertEquals("minBlockNum: 16000, blockNum: 10000", e2.getMessage()); } @Test @@ -148,15 +144,12 @@ public void testRateLimiter() { Mockito.when(peer.getP2pRateLimiter()).thenReturn(p2pRateLimiter); FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler(); - try { - fetchInvDataMsgHandler.processMessage(peer, msg); - } catch (Exception e) { - Assert.assertEquals("fetch too many blocks, size:101", e.getMessage()); - } - try { - fetchInvDataMsgHandler.processMessage(peer, msg); - } catch (Exception e) { - Assert.assertTrue(e.getMessage().endsWith("rate limit")); - } + Exception e1 = Assert.assertThrows(Exception.class, + () -> fetchInvDataMsgHandler.processMessage(peer, msg)); + Assert.assertEquals("fetch too many blocks, size:101", e1.getMessage()); + + Exception e2 = Assert.assertThrows(Exception.class, + () -> fetchInvDataMsgHandler.processMessage(peer, msg)); + Assert.assertTrue(e2.getMessage().endsWith("rate limit")); } } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java index 338b44e6699..1dbf7c7150f 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java @@ -49,6 +49,7 @@ public void testProcessMessage() throws Exception { field.set(handler, tronNetDelegate); handler.processMessage(peer, msg); + Mockito.verify(tronNetDelegate, Mockito.atLeastOnce()).isBlockUnsolidified(); } private Channel getChannel(String host, int port) throws Exception { diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java index b1fb197a2e9..be843674632 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java @@ -13,13 +13,13 @@ import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import org.springframework.context.ApplicationContext; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.consensus.pbft.message.PbftMessage; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.net.P2pEventHandlerImpl; import org.tron.core.net.TronNetService; @@ -33,6 +33,8 @@ public class MessageHandlerTest { private static TronApplicationContext context; + private static final ClassLevelAppContextFixture APP_FIXTURE = + new ClassLevelAppContextFixture(); private PeerConnection peer; private static P2pEventHandlerImpl p2pEventHandler; private static ApplicationContext ctx; @@ -45,7 +47,7 @@ public class MessageHandlerTest { public static void init() throws Exception { Args.setParam(new String[] {"--output-directory", temporaryFolder.newFolder().toString(), "--debug"}, TestConstants.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + context = APP_FIXTURE.createContext(); p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); @@ -57,7 +59,7 @@ public static void init() throws Exception { @AfterClass public static void destroy() { Args.clearParam(); - context.destroy(); + APP_FIXTURE.close(); } @After diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java index 80b1abdc35d..fc0718e1d2d 100644 --- a/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java +++ b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java @@ -1,11 +1,18 @@ package org.tron.core.net.peer; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import org.junit.After; +import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; +import org.tron.common.utils.ReflectUtils; public class PeerStatusCheckMockTest { @After @@ -14,13 +21,26 @@ public void clearMocks() { } @Test - public void testInitException() throws InterruptedException { + public void testInitException() { PeerStatusCheck peerStatusCheck = spy(new PeerStatusCheck()); + ScheduledExecutorService executor = mock(ScheduledExecutorService.class); + ReflectUtils.setFieldValue(peerStatusCheck, "peerStatusCheckExecutor", executor); doThrow(new RuntimeException("test exception")).when(peerStatusCheck).statusCheck(); + peerStatusCheck.init(); - // the initialDelay of scheduleWithFixedDelay is 5s - Thread.sleep(5000L); + Mockito.verify(executor).scheduleWithFixedDelay(any(Runnable.class), eq(5L), eq(2L), + eq(TimeUnit.SECONDS)); + Runnable scheduledTask = Mockito.mockingDetails(executor).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals("scheduleWithFixedDelay")) + .map(invocation -> (Runnable) invocation.getArgument(0)) + .findFirst() + .orElseThrow(() -> new AssertionError("scheduled task was not registered")); + + scheduledTask.run(); + + Mockito.verify(peerStatusCheck).statusCheck(); + Assert.assertNotNull(peerStatusCheck); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java index 6f34288939f..8585244b941 100644 --- a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java @@ -89,7 +89,6 @@ private void initWitness() { // Base58: TNboetpFgv9SqMoHvaVt626NLXETnbdW1K byte[] key = Hex.decode("418A8D690BF36806C36A7DAE3AF796643C1AA9CC01");//exist already WitnessCapsule witnessCapsule = chainBaseManager.getWitnessStore().get(key); - System.out.println(witnessCapsule.getInstance()); witnessCapsule.setVoteCount(1000); chainBaseManager.getWitnessStore().put(key, witnessCapsule); List list = new ArrayList<>(); diff --git a/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java b/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java index a940a14d392..7ad56c464bb 100644 --- a/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java +++ b/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java @@ -7,8 +7,10 @@ import org.junit.Assert; import org.junit.Test; +import org.tron.core.net.TronNetService; import org.tron.core.net.service.statistics.NodeStatistics; import org.tron.core.net.service.statistics.TronStatsManager; +import org.tron.p2p.stats.P2pStats; import org.tron.protos.Protocol; public class TronStatsManagerTest { @@ -50,14 +52,20 @@ public void testWork() throws Exception { Assert.assertEquals(field3.get(manager), 1L); Assert.assertEquals(field4.get(manager), 1L); + P2pStats statsSnapshot = TronNetService.getP2pService().getP2pStats(); + long expectedTcpIn = statsSnapshot.getTcpInSize(); + long expectedTcpOut = statsSnapshot.getTcpOutSize(); + long expectedUdpIn = statsSnapshot.getUdpInSize(); + long expectedUdpOut = statsSnapshot.getUdpOutSize(); + Method method = manager.getClass().getDeclaredMethod("work"); method.setAccessible(true); method.invoke(manager); - Assert.assertEquals(field1.get(manager), 0L); - Assert.assertEquals(field2.get(manager), 0L); - Assert.assertEquals(field3.get(manager), 0L); - Assert.assertEquals(field4.get(manager), 0L); + Assert.assertEquals(expectedTcpIn, (long) field1.get(manager)); + Assert.assertEquals(expectedTcpOut, (long) field2.get(manager)); + Assert.assertEquals(expectedUdpIn, (long) field3.get(manager)); + Assert.assertEquals(expectedUdpOut, (long) field4.get(manager)); } } diff --git a/framework/src/test/java/org/tron/core/pbft/PbftTest.java b/framework/src/test/java/org/tron/core/pbft/PbftTest.java index 33a46516988..10965240c8e 100644 --- a/framework/src/test/java/org/tron/core/pbft/PbftTest.java +++ b/framework/src/test/java/org/tron/core/pbft/PbftTest.java @@ -30,7 +30,7 @@ public void testPbftSrMessage() { PbftMessage pbftSrMessage = PbftMessage .prePrepareSRLMsg(blockCapsule, srList, 1, miner); PbftMessage.fullNodePrePrepareSRLMsg(blockCapsule, srList, 1); - System.out.println(pbftSrMessage); + org.junit.Assert.assertNotNull(pbftSrMessage); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java b/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java index 7617af2c1eb..a1bffd5bf1f 100644 --- a/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java +++ b/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java @@ -12,7 +12,9 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.Assert; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.Timeout; import org.tron.common.BaseMethodTest; import org.tron.common.error.TronDBException; import org.tron.common.es.ExecutorServiceManager; @@ -33,6 +35,11 @@ public class ComputeRewardTest extends BaseMethodTest { + // setUp() contains a 6-second sleep waiting for async reward calculation; + // 60 s total budget covers setup + test body with headroom for slow CI. + @Rule + public Timeout timeout = Timeout.seconds(60); + private static final byte[] OWNER_ADDRESS = ByteArray.fromHexString( "4105b9e8af8ee371cad87317f442d155b39fbd1bf0"); diff --git a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java index fc60c2afa03..a16a71c4e59 100644 --- a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java @@ -78,7 +78,6 @@ private void testWithdraw() { mortgageService.withdrawReward(sr1); accountCapsule = dbManager.getAccountStore().get(sr1); allowance = accountCapsule.getAllowance() - allowance; - System.out.println("withdrawReward:" + allowance); Assert.assertEquals(reward, allowance); } diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java index f40ec48e035..94b05cae98f 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -51,9 +51,8 @@ import org.tron.api.WalletGrpc.WalletBlockingStub; import org.tron.api.WalletSolidityGrpc; import org.tron.api.WalletSolidityGrpc.WalletSolidityBlockingStub; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.es.ExecutorServiceManager; import org.tron.common.utils.ByteArray; @@ -65,7 +64,6 @@ import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.Manager; import org.tron.protos.Protocol; @@ -118,8 +116,9 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RpcApiServicesTest { - private static Application appTest; private static TronApplicationContext context; + private static final ClassLevelAppContextFixture APP_FIXTURE = + new ClassLevelAppContextFixture(); private static ManagedChannel channelFull = null; private static ManagedChannel channelPBFT = null; private static ManagedChannel channelSolidity = null; @@ -188,7 +187,7 @@ public static void init() throws IOException { .executor(executorService) .intercept(new TimeoutInterceptor(5000)) .build(); - context = new TronApplicationContext(DefaultConfig.class); + context = APP_FIXTURE.createContext(); databaseBlockingStubFull = DatabaseGrpc.newBlockingStub(channelFull); databaseBlockingStubSolidity = DatabaseGrpc.newBlockingStub(channelSolidity); databaseBlockingStubPBFT = DatabaseGrpc.newBlockingStub(channelPBFT); @@ -204,15 +203,12 @@ public static void init() throws IOException { manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); manager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); manager.getDynamicPropertiesStore().saveAllowShieldedTRC20Transaction(1); - appTest = ApplicationFactory.create(context); - appTest.startup(); + APP_FIXTURE.startApp(); } @AfterClass public static void destroy() { - shutdownChannel(channelFull); - shutdownChannel(channelPBFT); - shutdownChannel(channelSolidity); + ClassLevelAppContextFixture.shutdownChannels(channelFull, channelPBFT, channelSolidity); if (executorService != null) { ExecutorServiceManager.shutdownAndAwaitTermination( @@ -220,25 +216,10 @@ public static void destroy() { executorService = null; } - context.close(); + APP_FIXTURE.close(); Args.clearParam(); } - private static void shutdownChannel(ManagedChannel channel) { - if (channel == null) { - return; - } - try { - channel.shutdown(); - if (!channel.awaitTermination(5, TimeUnit.SECONDS)) { - channel.shutdownNow(); - } - } catch (InterruptedException e) { - channel.shutdownNow(); - Thread.currentThread().interrupt(); - } - } - @Test public void testGetBlockByNum() { NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); diff --git a/framework/src/test/java/org/tron/core/services/WalletApiTest.java b/framework/src/test/java/org/tron/core/services/WalletApiTest.java index b7a26d6dc73..4a55556afb1 100644 --- a/framework/src/test/java/org/tron/core/services/WalletApiTest.java +++ b/framework/src/test/java/org/tron/core/services/WalletApiTest.java @@ -14,13 +14,11 @@ import org.junit.rules.Timeout; import org.tron.api.GrpcAPI.EmptyMessage; import org.tron.api.WalletGrpc; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.PublicMethod; import org.tron.common.utils.TimeoutInterceptor; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @@ -34,7 +32,8 @@ public class WalletApiTest { public Timeout timeout = new Timeout(30, TimeUnit.SECONDS); private static TronApplicationContext context; - private static Application appT; + private static final ClassLevelAppContextFixture APP_FIXTURE = + new ClassLevelAppContextFixture(); @BeforeClass @@ -43,9 +42,7 @@ public static void init() throws IOException { "--p2p-disable", "true"}, TestConstants.TEST_CONF); Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); Args.getInstance().setRpcEnable(true); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); - appT.startup(); + context = APP_FIXTURE.createAndStart(); } @Test @@ -61,22 +58,13 @@ public void listNodesTest() { Assert.assertTrue(walletStub.listNodes(EmptyMessage.getDefaultInstance()) .getNodesList().isEmpty()); } finally { - // Properly shutdown the gRPC channel to prevent resource leaks - channel.shutdown(); - try { - if (!channel.awaitTermination(5, java.util.concurrent.TimeUnit.SECONDS)) { - channel.shutdownNow(); - } - } catch (InterruptedException e) { - channel.shutdownNow(); - Thread.currentThread().interrupt(); - } + ClassLevelAppContextFixture.shutdownChannel(channel); } } @AfterClass public static void destroy() { - context.destroy(); + APP_FIXTURE.close(); Args.clearParam(); } diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java index 42ed21312c3..5feaf0e5223 100644 --- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java @@ -18,21 +18,21 @@ import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.PublicMethod; import org.tron.common.utils.TimeoutInterceptor; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @Slf4j public class LiteFnQueryGrpcInterceptorTest { private static TronApplicationContext context; + private static final ClassLevelAppContextFixture APP_FIXTURE = + new ClassLevelAppContextFixture(); private static ManagedChannel channelFull = null; private static ManagedChannel channelSolidity = null; private static ManagedChannel channelpBFT = null; @@ -84,30 +84,21 @@ public static void init() throws IOException { .usePlaintext() .intercept(new TimeoutInterceptor(5000)) .build(); - context = new TronApplicationContext(DefaultConfig.class); + context = APP_FIXTURE.createContext(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); blockingStubpBFT = WalletSolidityGrpc.newBlockingStub(channelpBFT); chainBaseManager = context.getBean(ChainBaseManager.class); - Application appTest = ApplicationFactory.create(context); - appTest.startup(); + APP_FIXTURE.startApp(); } /** * destroy the context. */ @AfterClass - public static void destroy() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdownNow(); - } - if (channelSolidity != null) { - channelSolidity.shutdownNow(); - } - if (channelpBFT != null) { - channelpBFT.shutdownNow(); - } - context.close(); + public static void destroy() { + ClassLevelAppContextFixture.shutdownChannels(channelFull, channelSolidity, channelpBFT); + APP_FIXTURE.close(); Args.clearParam(); } diff --git a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java index 817693dc630..07821d10343 100644 --- a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java @@ -31,14 +31,12 @@ import org.tron.api.GrpcAPI.TransactionIdList; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.common.TestConstants; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.PublicMethod; import org.tron.common.utils.TimeoutInterceptor; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; import org.tron.protos.Protocol.Transaction; @@ -47,6 +45,8 @@ public class RpcApiAccessInterceptorTest { private static TronApplicationContext context; + private static final ClassLevelAppContextFixture APP_FIXTURE = + new ClassLevelAppContextFixture(); private static ManagedChannel channelFull = null; private static ManagedChannel channelPBFT = null; private static ManagedChannel channelSolidity = null; @@ -93,14 +93,13 @@ public static void init() throws IOException { .intercept(new TimeoutInterceptor(5000)) .build(); - context = new TronApplicationContext(DefaultConfig.class); + context = APP_FIXTURE.createContext(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); blockingStubPBFT = WalletSolidityGrpc.newBlockingStub(channelPBFT); - Application appTest = ApplicationFactory.create(context); - appTest.startup(); + APP_FIXTURE.startApp(); } /** @@ -108,16 +107,8 @@ public static void init() throws IOException { */ @AfterClass public static void destroy() { - if (channelFull != null) { - channelFull.shutdownNow(); - } - if (channelPBFT != null) { - channelPBFT.shutdownNow(); - } - if (channelSolidity != null) { - channelSolidity.shutdownNow(); - } - context.close(); + ClassLevelAppContextFixture.shutdownChannels(channelFull, channelPBFT, channelSolidity); + APP_FIXTURE.close(); Args.clearParam(); } @@ -307,4 +298,3 @@ public void testGetMemoFee() { } } - diff --git a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java index 72ac126e394..22d8d50483f 100644 --- a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java +++ b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java @@ -3,9 +3,12 @@ import com.google.common.cache.Cache; import com.google.common.util.concurrent.RateLimiter; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.utils.ReflectUtils; import org.tron.core.services.ratelimiter.adapter.GlobalPreemptibleAdapter; import org.tron.core.services.ratelimiter.adapter.IPQPSRateLimiterAdapter; @@ -134,15 +137,16 @@ public void testQpsRateLimiterAdapter() { long t0 = System.currentTimeMillis(); CountDownLatch latch = new CountDownLatch(20); - for (int i = 0; i < 20; i++) { - Thread thread = new Thread(new AdaptorThread(latch, strategy)); - thread.start(); - } - + ExecutorService pool = ExecutorServiceManager.newFixedThreadPool("adaptor-test", 20); try { + for (int i = 0; i < 20; i++) { + pool.execute(new AdaptorThread(latch, strategy)); + } latch.await(); } catch (InterruptedException e) { - System.out.println(e.getMessage()); + Thread.currentThread().interrupt(); + } finally { + ExecutorServiceManager.shutdownAndAwaitTermination(pool, "adaptor-test"); } long t1 = System.currentTimeMillis(); Assert.assertTrue(t1 - t0 > 4000); diff --git a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorThread.java b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorThread.java index 4ffe732348e..afcf21e7510 100644 --- a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorThread.java +++ b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorThread.java @@ -19,7 +19,7 @@ public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { - System.out.println(e.getMessage()); + Thread.currentThread().interrupt(); } latch.countDown(); } diff --git a/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java b/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java index ea622213f45..5c365eb3ef0 100644 --- a/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java +++ b/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java @@ -9,15 +9,20 @@ import java.util.Collections; import java.util.HashSet; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockedConstruction; import org.mockito.junit.MockitoJUnitRunner; import org.reflections.Reflections; +import org.tron.common.es.ExecutorServiceManager; import org.tron.core.actuator.AbstractActuator; import org.tron.core.actuator.TransferActuator; import org.tron.core.config.args.Args; @@ -49,25 +54,32 @@ public void testAlreadyRegisteredSkipRegistration() { @Test public void testConcurrentAccessThreadSafe() throws InterruptedException { final int threadCount = 5; - Thread[] threads = new Thread[threadCount]; final AtomicBoolean testPassed = new AtomicBoolean(true); + ExecutorService executor = ExecutorServiceManager + .newFixedThreadPool("transaction-register-test", threadCount); + Future[] futures = new Future[threadCount]; + + try { + for (int i = 0; i < threadCount; i++) { + futures[i] = executor.submit(() -> { + try { + TransactionRegister.registerActuator(); + } catch (Throwable e) { + testPassed.set(false); + throw e; + } + }); + } - for (int i = 0; i < threadCount; i++) { - threads[i] = new Thread(() -> { + for (Future future : futures) { try { - TransactionRegister.registerActuator(); - } catch (Throwable e) { - testPassed.set(false); + future.get(); + } catch (ExecutionException e) { + Assert.fail("Concurrent registration should not throw: " + e.getCause()); } - }); - } - - for (Thread thread : threads) { - thread.start(); - } - - for (Thread thread : threads) { - thread.join(); + } + } finally { + ExecutorServiceManager.shutdownAndAwaitTermination(executor, "transaction-register-test"); } assertTrue("All threads should complete without exceptions", testPassed.get()); @@ -134,4 +146,4 @@ public void testThrowsTronError() { assertTrue(error.getMessage().contains("TransferActuator")); } } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java index 59f4e899d9f..7749cd4ee6a 100644 --- a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java +++ b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java @@ -17,6 +17,7 @@ import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; import org.tron.core.consensus.ProposalController; +import org.tron.core.exception.ItemNotFoundException; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Proposal; import org.tron.protos.Protocol.Proposal.State; @@ -29,7 +30,7 @@ public class ProposalControllerTest extends BaseTest { private static boolean init; static { - Args.setParam(new String[]{"-d", dbPath()}, TestConstants.TEST_CONF); + Args.setParam(new String[] {"-d", dbPath()}, TestConstants.TEST_CONF); } @Before @@ -66,7 +67,7 @@ public void testSetDynamicParameters() { } @Test - public void testProcessProposal() { + public void testProcessProposal() throws ItemNotFoundException { ProposalCapsule proposalCapsule = new ProposalCapsule( Proposal.newBuilder().build()); proposalCapsule.setState(State.PENDING); @@ -77,11 +78,7 @@ public void testProcessProposal() { proposalController.processProposal(proposalCapsule); - try { - proposalCapsule = dbManager.getProposalStore().get(key); - } catch (Exception ex) { - System.out.println(ex.getMessage()); - } + proposalCapsule = dbManager.getProposalStore().get(key); Assert.assertEquals(State.DISAPPROVED, proposalCapsule.getState()); proposalCapsule.setState(State.PENDING); @@ -92,11 +89,7 @@ public void testProcessProposal() { proposalController.processProposal(proposalCapsule); - try { - proposalCapsule = dbManager.getProposalStore().get(key); - } catch (Exception ex) { - System.out.println(ex.getMessage()); - } + proposalCapsule = dbManager.getProposalStore().get(key); Assert.assertEquals(State.DISAPPROVED, proposalCapsule.getState()); List activeWitnesses = Lists.newArrayList(); @@ -114,17 +107,13 @@ public void testProcessProposal() { dbManager.getProposalStore().put(key, proposalCapsule); proposalController.processProposal(proposalCapsule); - try { - proposalCapsule = dbManager.getProposalStore().get(key); - } catch (Exception ex) { - System.out.println(ex.getMessage()); - } + proposalCapsule = dbManager.getProposalStore().get(key); Assert.assertEquals(State.APPROVED, proposalCapsule.getState()); } @Test - public void testProcessProposals() { + public void testProcessProposals() throws ItemNotFoundException { ProposalCapsule proposalCapsule1 = new ProposalCapsule( Proposal.newBuilder().build()); proposalCapsule1.setState(State.APPROVED); @@ -163,11 +152,7 @@ public void testProcessProposals() { proposalController.processProposals(); - try { - proposalCapsule3 = dbManager.getProposalStore().get(proposalCapsule3.createDbKey()); - } catch (Exception ex) { - System.out.println(ex.getMessage()); - } + proposalCapsule3 = dbManager.getProposalStore().get(proposalCapsule3.createDbKey()); Assert.assertEquals(State.DISAPPROVED, proposalCapsule3.getState()); } @@ -181,26 +166,26 @@ public void testHasMostApprovals() { List activeWitnesses = Lists.newArrayList(); for (int i = 0; i < 27; i++) { - activeWitnesses.add(ByteString.copyFrom(new byte[]{(byte) i})); + activeWitnesses.add(ByteString.copyFrom(new byte[] {(byte) i})); } for (int i = 0; i < 18; i++) { - proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); + proposalCapsule.addApproval(ByteString.copyFrom(new byte[] {(byte) i})); } Assert.assertTrue(proposalCapsule.hasMostApprovals(activeWitnesses)); proposalCapsule.clearApproval(); for (int i = 1; i < 18; i++) { - proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); + proposalCapsule.addApproval(ByteString.copyFrom(new byte[] {(byte) i})); } activeWitnesses.clear(); for (int i = 0; i < 5; i++) { - activeWitnesses.add(ByteString.copyFrom(new byte[]{(byte) i})); + activeWitnesses.add(ByteString.copyFrom(new byte[] {(byte) i})); } proposalCapsule.clearApproval(); for (int i = 0; i < 3; i++) { - proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); + proposalCapsule.addApproval(ByteString.copyFrom(new byte[] {(byte) i})); } Assert.assertTrue(proposalCapsule.hasMostApprovals(activeWitnesses)); } diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java index 3fe2ce02b63..58c5c905b15 100644 --- a/framework/src/test/java/org/tron/keystore/CredentialsTest.java +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -1,48 +1,76 @@ package org.tron.keystore; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import junit.framework.TestCase; -import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; import org.junit.Test; -import org.springframework.util.Assert; -import org.tron.common.crypto.SignUtils; +import org.mockito.Mockito; +import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.StringUtil; -@Slf4j -public class CredentialsTest extends TestCase { +public class CredentialsTest { + + private static final byte[] ADDRESS_1 = ByteUtil.hexToBytes( + "410102030405060708090a0b0c0d0e0f1011121314"); + private static final byte[] ADDRESS_2 = ByteUtil.hexToBytes( + "411415161718191a1b1c1d1e1f2021222324252627"); + + private SignInterface mockSignInterface(byte[] address) { + SignInterface signInterface = Mockito.mock(SignInterface.class); + Mockito.when(signInterface.getAddress()).thenReturn(address); + return signInterface; + } @Test - public void testCreate() throws NoSuchAlgorithmException { - Credentials credentials = Credentials.create(SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); - Assert.hasText(credentials.getAddress(),"Credentials address create failed!"); - Assert.notNull(credentials.getSignInterface(), - "Credentials cryptoEngine create failed"); + public void testCreate() { + SignInterface signInterface = mockSignInterface(ADDRESS_1); + Credentials credentials = Credentials.create(signInterface); + Assert.assertEquals("Credentials address create failed!", + StringUtil.encode58Check(ADDRESS_1), credentials.getAddress()); + Assert.assertSame("Credentials cryptoEngine create failed", signInterface, + credentials.getSignInterface()); } @Test public void testCreateFromSM2() { - try { - Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffffffffff"))); - } catch (Exception e) { - Assert.isInstanceOf(IllegalArgumentException.class, e); - } + Exception e = Assert.assertThrows(Exception.class, + () -> Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffffffffff")))); + Assert.assertTrue(e instanceof IllegalArgumentException); } @Test - public void testEquals() throws NoSuchAlgorithmException { - Credentials credentials1 = Credentials.create(SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); - Credentials credentials2 = Credentials.create(SignUtils.getGeneratedRandomSign( - SecureRandom.getInstance("NativePRNG"),true)); - Assert.isTrue(!credentials1.equals(credentials2), - "Credentials instance should be not equal!"); - Assert.isTrue(!(credentials1.hashCode() == credentials2.hashCode()), - "Credentials instance hashcode should be not equal!"); + public void testEquals() { + Credentials credentials1 = Credentials.create(mockSignInterface(ADDRESS_1)); + Credentials credentials2 = Credentials.create(mockSignInterface(ADDRESS_2)); + + Assert.assertNotEquals("Credentials address fixtures should differ", + credentials1.getAddress(), credentials2.getAddress()); + Assert.assertNotEquals("Credentials instance should be not equal!", + credentials1, credentials2); + } + + @Test + public void testEqualsWithAddressAndCryptoEngine() { + Object aObject = new Object(); + SignInterface signInterface = mockSignInterface(ADDRESS_1); + SignInterface signInterface2 = mockSignInterface(ADDRESS_1); + SignInterface signInterface3 = mockSignInterface(ADDRESS_2); + + Credentials credential = Credentials.create(signInterface); + Credentials sameCredential = Credentials.create(signInterface); + Credentials sameAddressDifferentEngineCredential = Credentials.create(signInterface2); + Credentials differentCredential = Credentials.create(signInterface3); + + Assert.assertFalse(aObject.equals(credential)); + Assert.assertFalse(credential.equals(aObject)); + Assert.assertFalse(credential.equals(null)); + Assert.assertEquals(credential, sameCredential); + Assert.assertEquals("Equal credentials must have the same hashCode", + credential.hashCode(), sameCredential.hashCode()); + Assert.assertNotEquals(credential, sameAddressDifferentEngineCredential); + Assert.assertFalse(credential.equals(differentCredential)); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/keystroe/CredentialsTest.java b/framework/src/test/java/org/tron/keystroe/CredentialsTest.java deleted file mode 100644 index 2642129e00a..00000000000 --- a/framework/src/test/java/org/tron/keystroe/CredentialsTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.tron.keystroe; - -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; -import org.tron.common.crypto.SignInterface; -import org.tron.keystore.Credentials; - -public class CredentialsTest { - - @Test - public void test_equality() { - Object aObject = new Object(); - SignInterface si = Mockito.mock(SignInterface.class); - SignInterface si2 = Mockito.mock(SignInterface.class); - SignInterface si3 = Mockito.mock(SignInterface.class); - byte[] address = "TQhZ7W1RudxFdzJMw6FvMnujPxrS6sFfmj".getBytes(); - byte[] address2 = "TNCmcTdyrYKMtmE1KU2itzeCX76jGm5Not".getBytes(); - Mockito.when(si.getAddress()).thenReturn(address); - Mockito.when(si2.getAddress()).thenReturn(address); - Mockito.when(si3.getAddress()).thenReturn(address2); - Credentials aCredential = Credentials.create(si); - Assert.assertFalse(aObject.equals(aCredential)); - Assert.assertFalse(aCredential.equals(aObject)); - Assert.assertFalse(aCredential.equals(null)); - Credentials anotherCredential = Credentials.create(si); - Assert.assertTrue(aCredential.equals(anotherCredential)); - Credentials aCredential2 = Credentials.create(si2); - Assert.assertTrue(aCredential.equals(anotherCredential)); - Credentials aCredential3 = Credentials.create(si3); - Assert.assertFalse(aCredential.equals(aCredential3)); - } -} diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 7d94f813b80..782f934d686 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -1,7 +1,11 @@ package org.tron.program; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; import java.util.concurrent.TimeUnit; import javax.annotation.Resource; @@ -10,8 +14,10 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; +import org.mockito.InOrder; import org.tron.common.BaseTest; import org.tron.common.TestConstants; +import org.tron.common.application.Application; import org.tron.common.client.DatabaseGrpcClient; import org.tron.common.utils.PublicMethod; import org.tron.core.config.args.Args; @@ -89,4 +95,32 @@ public void testSolidityNodeHttpApiService() { solidityNodeHttpApiService.stop(); Assert.assertTrue(true); } + + @Test + public void testAwaitShutdownAlwaysStopsNode() { + Application app = mock(Application.class); + SolidityNode node = mock(SolidityNode.class); + + SolidityNode.awaitShutdown(app, node); + + InOrder inOrder = inOrder(app, node); + inOrder.verify(app).blockUntilShutdown(); + inOrder.verify(node).shutdown(); + } + + @Test + public void testAwaitShutdownStopsNodeWhenBlockedCallFails() { + Application app = mock(Application.class); + SolidityNode node = mock(SolidityNode.class); + RuntimeException expected = new RuntimeException("boom"); + doThrow(expected).when(app).blockUntilShutdown(); + + RuntimeException thrown = assertThrows(RuntimeException.class, + () -> SolidityNode.awaitShutdown(app, node)); + assertSame(expected, thrown); + + InOrder inOrder = inOrder(app, node); + inOrder.verify(app).blockUntilShutdown(); + inOrder.verify(node).shutdown(); + } } diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteTest.java b/plugins/src/test/java/org/tron/plugins/DbLiteTest.java index 60db838a80d..07bddc461a0 100644 --- a/plugins/src/test/java/org/tron/plugins/DbLiteTest.java +++ b/plugins/src/test/java/org/tron/plugins/DbLiteTest.java @@ -90,7 +90,6 @@ public void clear() { public void testTools(String dbType, int checkpointVersion) throws InterruptedException, IOException { logger.info("dbType {}, checkpointVersion {}", dbType, checkpointVersion); - dbPath = String.format("%s_%s_%d", dbPath, dbType, System.currentTimeMillis()); init(dbType); final String[] argsForSnapshot = new String[] {"-o", "split", "-t", "snapshot", "--fn-data-path", @@ -166,7 +165,8 @@ private void generateSomeTransactions(int during) { try { Thread.sleep(sleepOnce); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + return; } if ((runTime += sleepOnce) > during) { return; diff --git a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java index 5b25739f272..ec4f0d545b0 100644 --- a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java +++ b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java @@ -31,7 +31,6 @@ private void init(DbTool.DbType dbType, String path) throws IOException, RocksDB DbTool.getDB(path, ACCOUNT, dbType).close(); DbTool.getDB(path, DBUtils.MARKET_PAIR_PRICE_TO_ORDER, dbType).close(); DbTool.getDB(path, TRANS, dbType).close(); - } @After diff --git a/plugins/src/test/java/org/tron/plugins/DbTest.java b/plugins/src/test/java/org/tron/plugins/DbTest.java index bbcc1a0bbf7..d22addfbae8 100644 --- a/plugins/src/test/java/org/tron/plugins/DbTest.java +++ b/plugins/src/test/java/org/tron/plugins/DbTest.java @@ -18,10 +18,10 @@ public class DbTest { - public String INPUT_DIRECTORY; + protected String INPUT_DIRECTORY; private static final String ACCOUNT = "account"; private static final String MARKET = DBUtils.MARKET_PAIR_PRICE_TO_ORDER; - public CommandLine cli = new CommandLine(new Toolkit()); + protected CommandLine cli = new CommandLine(new Toolkit()); @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); diff --git a/plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java b/plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java index f5880d82e39..ff73eca25cc 100644 --- a/plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java +++ b/plugins/src/test/java/org/tron/plugins/leveldb/ArchiveManifestTest.java @@ -1,16 +1,7 @@ package org.tron.plugins.leveldb; -import java.io.BufferedReader; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; -import java.util.Properties; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; @@ -82,41 +73,4 @@ public void testEmpty() { Assert.assertEquals(0, ArchiveManifest.run(args)); } - private static void writeProperty(String filename, String key, String value) throws IOException { - File file = new File(filename); - if (!file.exists()) { - file.createNewFile(); - } - - try (FileInputStream fis = new FileInputStream(file); - OutputStream out = new FileOutputStream(file); - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, - StandardCharsets.UTF_8))) { - BufferedReader bf = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); - Properties properties = new Properties(); - properties.load(bf); - properties.setProperty(key, value); - properties.store(bw, "Generated by the application. PLEASE DO NOT EDIT! "); - } catch (Exception e) { - logger.warn("{}", e); - } - } - - /** - * delete directory. - */ - private static boolean deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - assert children != null; - for (String child : children) { - boolean success = deleteDir(new File(dir, child)); - if (!success) { - logger.warn("can't delete dir:" + dir); - return false; - } - } - } - return dir.delete(); - } } diff --git a/plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java b/plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java index 69dca01e4f8..8c20c2b55be 100644 --- a/plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java +++ b/plugins/src/test/java/org/tron/plugins/leveldb/DbArchiveTest.java @@ -1,16 +1,7 @@ package org.tron.plugins.leveldb; -import java.io.BufferedReader; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; -import java.util.Properties; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; @@ -88,41 +79,4 @@ public void testEmpty() { Assert.assertEquals(0, cli.execute(args)); } - private static void writeProperty(String filename, String key, String value) throws IOException { - File file = new File(filename); - if (!file.exists()) { - file.createNewFile(); - } - - try (FileInputStream fis = new FileInputStream(file); - OutputStream out = new FileOutputStream(file); - BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, - StandardCharsets.UTF_8))) { - BufferedReader bf = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); - Properties properties = new Properties(); - properties.load(bf); - properties.setProperty(key, value); - properties.store(bw, "Generated by the application. PLEASE DO NOT EDIT! "); - } catch (Exception e) { - logger.warn("{}", e); - } - } - - /** - * delete directory. - */ - private static boolean deleteDir(File dir) { - if (dir.isDirectory()) { - String[] children = dir.list(); - assert children != null; - for (String child : children) { - boolean success = deleteDir(new File(dir, child)); - if (!success) { - logger.warn("can't delete dir:" + dir); - return false; - } - } - } - return dir.delete(); - } } diff --git a/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java b/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java index ab1067fefc3..ebc4074ccc0 100644 --- a/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java +++ b/plugins/src/test/java/org/tron/plugins/rocksdb/DbLiteRocksDbV2Test.java @@ -7,7 +7,7 @@ public class DbLiteRocksDbV2Test extends DbLiteTest { @Test - public void testToolsWithRocksDB() throws InterruptedException, IOException { + public void testToolsWithRocksDbV2() throws InterruptedException, IOException { testTools("ROCKSDB", 2); } }