From 15a1d7b8c9eeb362cf21c368942954a3a02b6f1b Mon Sep 17 00:00:00 2001 From: GrapeS Date: Mon, 6 Apr 2026 16:23:02 +0800 Subject: [PATCH 01/28] test(framework): fix test quality issues in framework unit tests - FetchInvDataMsgHandlerTest: add Assert.fail() before catch blocks so tests fail when expected exceptions are not thrown; fix assertEquals argument order (expected, actual) - ConcurrentHashMapTest: restore commented-out Assert.fail() for ItemNotFoundException; replace printStackTrace() with interrupt flag restoration and proper logging; fail main thread on interrupted join - InventoryMsgHandlerTest: add Mockito.verify() to assert isBlockUnsolidified() is called in the unsolidified-block scenario - PeerStatusCheckMockTest: add Mockito.verify() to assert statusCheck() is invoked by the scheduler after init() - MerkleTreeTest: replace Assert.assertFalse(true) with Assert.fail() for clearer failure message Co-Authored-By: Claude Sonnet 4.6 --- .../core/capsule/utils/MerkleTreeTest.java | 2 +- .../core/jsonrpc/ConcurrentHashMapTest.java | 25 +++++++++++-------- .../FetchInvDataMsgHandlerTest.java | 8 ++++-- .../InventoryMsgHandlerTest.java | 1 + .../net/peer/PeerStatusCheckMockTest.java | 7 +++++- 5 files changed, 29 insertions(+), 14 deletions(-) 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..247a52e648f 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 @@ -103,7 +103,7 @@ public void test0HashNum() { List hashList = getHash(0); //Empty list. try { MerkleTree.getInstance().createTree(hashList); - Assert.assertFalse(true); + Assert.fail("Expected IndexOutOfBoundsException for empty hash list"); } catch (Exception e) { Assert.assertTrue(e instanceof IndexOutOfBoundsException); } 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..1c11a2a35dd 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java @@ -52,7 +52,8 @@ 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() { @@ -69,7 +70,8 @@ public void run() { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + logger.error("putThread interrupted", e); } } } @@ -83,7 +85,8 @@ public void run() { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + logger.error("getThread1 interrupted", e); } logger.info("Thread1 get time {}", t); @@ -98,8 +101,7 @@ public void run() { } } catch (ItemNotFoundException e) { - e.printStackTrace(); - // Assert.fail(e.getMessage()); + Assert.fail("Filter ID should always exist: " + e.getMessage()); } } } @@ -113,7 +115,8 @@ public void run() { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + logger.error("getThread2 interrupted", e); } logger.info("Thread2 get time {}", t); @@ -132,7 +135,7 @@ public void run() { } } catch (ItemNotFoundException e) { - // Assert.fail(e.getMessage()); + Assert.fail("Filter ID should always exist: " + e.getMessage()); } } } @@ -146,7 +149,8 @@ public void run() { try { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + logger.error("getThread3 interrupted", e); } logger.info("Thread3 get time {}", t); @@ -166,7 +170,7 @@ public void run() { } } catch (ItemNotFoundException e) { - // Assert.fail(e.getMessage()); + Assert.fail("Filter ID should always exist: " + e.getMessage()); } } } @@ -184,7 +188,8 @@ public void run() { getThread2.join(); getThread3.join(); } catch (InterruptedException e) { - e.printStackTrace(); + Thread.currentThread().interrupt(); + Assert.fail("Main thread interrupted while waiting for worker threads: " + e.getMessage()); } logger.info("-----------------------------------------------------------------------"); 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..f8677b6bc04 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 @@ -115,16 +115,18 @@ public void testSyncFetchCheck() { Mockito.when(peer.getLastSyncBlockId()) .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1000L)); fetchInvDataMsgHandler.processMessage(peer, msg); + Assert.fail("Expected exception was not thrown: maxBlockNum: 1000, blockNum: 10000"); } catch (Exception e) { - Assert.assertEquals(e.getMessage(), "maxBlockNum: 1000, blockNum: 10000"); + Assert.assertEquals("maxBlockNum: 1000, blockNum: 10000", e.getMessage()); } try { Mockito.when(peer.getLastSyncBlockId()) .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 20000L)); fetchInvDataMsgHandler.processMessage(peer, msg); + Assert.fail("Expected exception was not thrown: minBlockNum: 16000, blockNum: 10000"); } catch (Exception e) { - Assert.assertEquals(e.getMessage(), "minBlockNum: 16000, blockNum: 10000"); + Assert.assertEquals("minBlockNum: 16000, blockNum: 10000", e.getMessage()); } } @@ -150,11 +152,13 @@ public void testRateLimiter() { try { fetchInvDataMsgHandler.processMessage(peer, msg); + Assert.fail("Expected exception was not thrown: fetch too many blocks, size:101"); } catch (Exception e) { Assert.assertEquals("fetch too many blocks, size:101", e.getMessage()); } try { fetchInvDataMsgHandler.processMessage(peer, msg); + Assert.fail("Expected rate limit exception was not thrown"); } catch (Exception e) { Assert.assertTrue(e.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/peer/PeerStatusCheckMockTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java index 80b1abdc35d..c518e22280b 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 @@ -4,6 +4,7 @@ import static org.mockito.Mockito.spy; import org.junit.After; +import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; @@ -19,8 +20,12 @@ public void testInitException() throws InterruptedException { doThrow(new RuntimeException("test exception")).when(peerStatusCheck).statusCheck(); peerStatusCheck.init(); - // the initialDelay of scheduleWithFixedDelay is 5s + // the initialDelay of scheduleWithFixedDelay is 5s; wait for at least one execution Thread.sleep(5000L); + + // Verify statusCheck() was invoked by the scheduler and the exception was handled gracefully + Mockito.verify(peerStatusCheck, Mockito.atLeastOnce()).statusCheck(); + Assert.assertNotNull(peerStatusCheck); } } \ No newline at end of file From 6964695069727bd534a6ac1765f527bb668150f5 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Mon, 6 Apr 2026 16:33:52 +0800 Subject: [PATCH 02/28] test(plugins): fix test quality issues in plugins unit tests - DbLiteTest: remove dead null-dbPath reassignment before init() call; restore thread interrupt flag on InterruptedException in generateSomeTransactions() - DbMoveTest: remove legacy @After destroy() that cleaned a hardcoded path never written by any test; remove dead deleteDir() helper and OUTPUT_DIRECTORY constant; remove now-unused After import - DbTest: narrow INPUT_DIRECTORY and cli fields from public to protected - ArchiveManifestTest, DbArchiveTest: remove copy-pasted writeProperty() and deleteDir() private static methods that were never called; clean up unused imports - DbLiteRocksDbV2Test: rename testToolsWithRocksDB to testToolsWithRocksDbV2 to match the LevelDB v1/v2 naming convention Note: testMvForRocksDB is a pre-existing failure unrelated to these changes. Co-Authored-By: Claude Sonnet 4.6 --- .../java/org/tron/plugins/DbLiteTest.java | 4 +- .../java/org/tron/plugins/DbMoveTest.java | 27 ----------- .../test/java/org/tron/plugins/DbTest.java | 4 +- .../plugins/leveldb/ArchiveManifestTest.java | 46 ------------------- .../tron/plugins/leveldb/DbArchiveTest.java | 46 ------------------- .../plugins/rocksdb/DbLiteRocksDbV2Test.java | 2 +- 6 files changed, 5 insertions(+), 124 deletions(-) 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..6df17c4251c 100644 --- a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java +++ b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java @@ -5,7 +5,6 @@ import java.net.URL; import java.nio.file.Paths; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -18,8 +17,6 @@ @Slf4j public class DbMoveTest { - private static final String OUTPUT_DIRECTORY = "output-directory-toolkit"; - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -31,30 +28,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 - public void destroy() { - deleteDir(new File(OUTPUT_DIRECTORY)); - } - - /** - * 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(); } private static String getConfig(String config) { 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); } } From ec640a6bb1b184163d04cd4ee8eff0e638c71149 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Mon, 6 Apr 2026 17:29:08 +0800 Subject: [PATCH 03/28] test(actuator): remove obsolete moreThanFrozenNumber test in FreezeBalanceActuatorTest The method tested a "max frozen number is: X" error that no longer exists in FreezeBalanceActuator. The actuator was updated to check "frozenCount must be 0 or 1" instead, and a second freeze with frozenCount=1 now succeeds rather than throwing. Remove the now-unused ChainConstant import. Co-Authored-By: Claude Sonnet 4.6 --- .../actuator/FreezeBalanceActuatorTest.java | 30 ------------------- 1 file changed, 30 deletions(-) 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(); From 4316815a3be56960c9058aef56ab63f87dafa47a Mon Sep 17 00:00:00 2001 From: GrapeS Date: Tue, 7 Apr 2026 12:10:29 +0800 Subject: [PATCH 04/28] test(framework): fix test cleanup and solidity node shutdown --- .../java/org/tron/program/SolidityNode.java | 32 +++++++++++++++--- .../logsfilter/NativeMessageQueueTest.java | 27 ++++++++++++--- .../core/jsonrpc/SectionBloomStoreTest.java | 18 ++++++++-- .../tron/core/services/ComputeRewardTest.java | 7 ++++ .../ratelimiter/adaptor/AdaptorTest.java | 16 +++++---- .../ratelimiter/adaptor/AdaptorThread.java | 2 +- .../org/tron/program/SolidityNodeTest.java | 33 +++++++++++++++++++ 7 files changed, 117 insertions(+), 18 deletions(-) diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index 3367141e2a5..de0bdaea1de 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) { @@ -193,4 +217,4 @@ private void resolveCompatibilityIssueIfUsingFullNodeDatabase() { chainBaseManager.getDynamicPropertiesStore().saveLatestSolidifiedBlockNum(headBlockNum); } } -} \ No newline at end of file +} 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/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/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/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/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 7d94f813b80..91e3b93fa96 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -2,6 +2,9 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.doThrow; import java.util.concurrent.TimeUnit; import javax.annotation.Resource; @@ -10,8 +13,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 +94,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)); + assertEquals(expected, thrown); + + InOrder inOrder = inOrder(app, node); + inOrder.verify(app).blockUntilShutdown(); + inOrder.verify(node).shutdown(); + } } From c4aac32626b9ced21a82180f9e9c16cf0903d555 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Thu, 23 Apr 2026 15:14:17 +0800 Subject: [PATCH 05/28] test(framework): replace bare Executors with ExecutorServiceManager and fix test quality issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace Executors.newFixedThreadPool / bare new Thread[] with ExecutorServiceManager in LogBlockQueryTest, TransactionRegisterTest, ConcurrentHashMapTest; add proper shutdownAndAwaitTermination - Fix InterruptedException handling: restore interrupt flag instead of swallowing in PropUtilTest, DBIteratorTest, SnapshotImplTest, ProposalControllerTest, BlockStoreTest, PbftTest - Remove dead/unreachable test code in FreezeTest, EventParserTest, EventParserJsonTest, BlockFilterCapsuleTest, MessageTest, RelayServiceTest, DelegationServiceTest - Fix package typo: rename keystroe.CredentialsTest → keystore.CredentialsTest; rewrite test using JUnit Assert and Mockito instead of junit.framework.TestCase - Minor cleanup: unused imports, whitespace, AccountAssetStoreTest assertion style Co-Authored-By: Claude Sonnet 4.6 --- .../logsfilter/EventParserJsonTest.java | 1 - .../common/logsfilter/EventParserTest.java | 1 - .../capsule/BlockFilterCapsuleTest.java | 1 - .../tron/common/runtime/vm/FreezeTest.java | 8 --- .../org/tron/common/utils/PropUtilTest.java | 6 +- .../tron/core/db/AccountAssetStoreTest.java | 2 +- .../java/org/tron/core/db/BlockStoreTest.java | 6 +- .../java/org/tron/core/db/DBIteratorTest.java | 59 +++++++-------- .../org/tron/core/db2/SnapshotImplTest.java | 3 +- .../core/jsonrpc/ConcurrentHashMapTest.java | 71 +++++++++---------- .../tron/core/jsonrpc/LogBlockQueryTest.java | 19 +++-- .../java/org/tron/core/net/MessageTest.java | 2 - .../core/net/services/RelayServiceTest.java | 1 - .../java/org/tron/core/pbft/PbftTest.java | 4 +- .../core/services/DelegationServiceTest.java | 1 - .../core/utils/TransactionRegisterTest.java | 44 +++++++----- .../core/witness/ProposalControllerTest.java | 8 +-- .../org/tron/keystore/CredentialsTest.java | 2 - 18 files changed, 111 insertions(+), 128 deletions(-) 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/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/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/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/db/AccountAssetStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java index 88734945687..24475f3c7f7 100644 --- a/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java @@ -87,7 +87,7 @@ private long createAsset(String tokenName) { try { ownerCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), TOTAL_SUPPLY); } catch (Exception e) { - e.printStackTrace(); + Assert.fail(e.getMessage()); } accountStore.put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); return id; 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/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/jsonrpc/ConcurrentHashMapTest.java b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java index 1c11a2a35dd..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); @@ -56,9 +61,10 @@ public void testHandleBlockHash() { 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); @@ -71,22 +77,19 @@ public void run() { Thread.sleep(randomInt(50, 100)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - logger.error("putThread interrupted", e); + 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) { Thread.currentThread().interrupt(); - logger.error("getThread1 interrupted", e); + throw new AssertionError("getThread1 interrupted", e); } logger.info("Thread1 get time {}", t); @@ -105,18 +108,16 @@ public void run() { } } } - } - }); + }); - 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) { Thread.currentThread().interrupt(); - logger.error("getThread2 interrupted", e); + throw new AssertionError("getThread2 interrupted", e); } logger.info("Thread2 get time {}", t); @@ -139,18 +140,16 @@ public void run() { } } } - } - }); + }); - 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) { Thread.currentThread().interrupt(); - logger.error("getThread3 interrupted", e); + throw new AssertionError("getThread3 interrupted", e); } logger.info("Thread3 get time {}", t); @@ -164,8 +163,7 @@ 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); } } @@ -174,22 +172,21 @@ public void run() { } } } + }); + + 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) { - Thread.currentThread().interrupt(); - Assert.fail("Main thread interrupted while waiting for worker threads: " + e.getMessage()); + } finally { + ExecutorServiceManager.shutdownAndAwaitTermination(executor, EXECUTOR_NAME); } logger.info("-----------------------------------------------------------------------"); @@ -210,4 +207,4 @@ public void run() { } } -} \ No newline at end of file +} 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..9f7f32d7201 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java @@ -3,13 +3,13 @@ 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; import org.junit.Before; import org.junit.Test; import org.tron.common.BaseTest; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.TestConstants; import org.tron.core.config.args.Args; import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; @@ -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/net/MessageTest.java b/framework/src/test/java/org/tron/core/net/MessageTest.java index 5b81d18a599..a2264545dc0 100644 --- a/framework/src/test/java/org/tron/core/net/MessageTest.java +++ b/framework/src/test/java/org/tron/core/net/MessageTest.java @@ -26,7 +26,6 @@ public void test1() throws Exception { disconnectMessage = new DisconnectMessage(MessageTypes.P2P_DISCONNECT.asByte(), disconnectMessageTest.toByteArray()); } catch (Exception e) { - System.out.println(e.getMessage()); Assert.assertTrue(e instanceof P2pException); } } @@ -39,7 +38,6 @@ public void test2() throws Exception { disconnectMessageTest.toByteArray()); } long endTime = System.currentTimeMillis(); - System.out.println("spend time : " + (endTime - startTime)); } @Test 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/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/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/utils/TransactionRegisterTest.java b/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java index ea622213f45..c57f7f42e2f 100644 --- a/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java +++ b/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java @@ -9,8 +9,12 @@ 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.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -18,6 +22,7 @@ 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..94e50b410a0 100644 --- a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java +++ b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java @@ -80,7 +80,7 @@ public void testProcessProposal() { try { proposalCapsule = dbManager.getProposalStore().get(key); } catch (Exception ex) { - System.out.println(ex.getMessage()); + Assert.fail(ex.getMessage()); } Assert.assertEquals(State.DISAPPROVED, proposalCapsule.getState()); @@ -95,7 +95,7 @@ public void testProcessProposal() { try { proposalCapsule = dbManager.getProposalStore().get(key); } catch (Exception ex) { - System.out.println(ex.getMessage()); + Assert.fail(ex.getMessage()); } Assert.assertEquals(State.DISAPPROVED, proposalCapsule.getState()); @@ -117,7 +117,7 @@ public void testProcessProposal() { try { proposalCapsule = dbManager.getProposalStore().get(key); } catch (Exception ex) { - System.out.println(ex.getMessage()); + Assert.fail(ex.getMessage()); } Assert.assertEquals(State.APPROVED, proposalCapsule.getState()); } @@ -166,7 +166,7 @@ public void testProcessProposals() { try { proposalCapsule3 = dbManager.getProposalStore().get(proposalCapsule3.createDbKey()); } catch (Exception ex) { - System.out.println(ex.getMessage()); + Assert.fail(ex.getMessage()); } Assert.assertEquals(State.DISAPPROVED, proposalCapsule3.getState()); diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java index 8aabd887bb0..97cb5d54139 100644 --- a/framework/src/test/java/org/tron/keystore/CredentialsTest.java +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -24,9 +24,7 @@ private SignInterface mockSignInterface(byte[] address) { @Test 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, From 0ac9b64463f1e926a6687908c4ea78eff2670159 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Tue, 7 Apr 2026 14:03:49 +0800 Subject: [PATCH 06/28] test(framework): unify app context fixtures in service tests --- .gitignore | 1 + .../common/ClassLevelAppContextFixture.java | 62 +++++++++++++++++++ .../messagehandler/MessageHandlerTest.java | 8 ++- .../core/services/RpcApiServicesTest.java | 33 +++------- .../org/tron/core/services/WalletApiTest.java | 24 ++----- .../LiteFnQueryGrpcInterceptorTest.java | 25 +++----- .../filter/RpcApiAccessInterceptorTest.java | 24 +++---- 7 files changed, 96 insertions(+), 81 deletions(-) create mode 100644 framework/src/test/java/org/tron/common/ClassLevelAppContextFixture.java diff --git a/.gitignore b/.gitignore index 3917bb44679..6587cb5b287 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,4 @@ Wallet /framework/propPath .cache +/.dev/ 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/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/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java index f40ec48e035..a4cb0dedde7 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -23,6 +23,7 @@ import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; import org.junit.runners.MethodSorters; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.api.DatabaseGrpc; import org.tron.api.DatabaseGrpc.DatabaseBlockingStub; import org.tron.api.GrpcAPI.BlockLimit; @@ -52,8 +53,6 @@ import org.tron.api.WalletSolidityGrpc; import org.tron.api.WalletSolidityGrpc.WalletSolidityBlockingStub; 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..555c763e566 100644 --- a/framework/src/test/java/org/tron/core/services/WalletApiTest.java +++ b/framework/src/test/java/org/tron/core/services/WalletApiTest.java @@ -12,15 +12,13 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; +import org.tron.common.ClassLevelAppContextFixture; import org.tron.api.GrpcAPI.EmptyMessage; import org.tron.api.WalletGrpc; 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() { } } - From 890e9b8978e6ee48662baad9ad8ac57d5bd7d8b2 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 15:20:44 +0800 Subject: [PATCH 07/28] style(test): fix import order to satisfy checkstyle Co-Authored-By: Claude Sonnet 4.6 --- .../src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java | 2 +- .../test/java/org/tron/core/services/RpcApiServicesTest.java | 2 +- .../src/test/java/org/tron/core/services/WalletApiTest.java | 2 +- .../test/java/org/tron/core/utils/TransactionRegisterTest.java | 2 +- framework/src/test/java/org/tron/program/SolidityNodeTest.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) 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 9f7f32d7201..94269e86fec 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/LogBlockQueryTest.java @@ -9,8 +9,8 @@ import org.junit.Before; import org.junit.Test; import org.tron.common.BaseTest; -import org.tron.common.es.ExecutorServiceManager; 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; 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 a4cb0dedde7..94b05cae98f 100644 --- a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -23,7 +23,6 @@ import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; import org.junit.runners.MethodSorters; -import org.tron.common.ClassLevelAppContextFixture; import org.tron.api.DatabaseGrpc; import org.tron.api.DatabaseGrpc.DatabaseBlockingStub; import org.tron.api.GrpcAPI.BlockLimit; @@ -52,6 +51,7 @@ 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.TronApplicationContext; import org.tron.common.es.ExecutorServiceManager; 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 555c763e566..4a55556afb1 100644 --- a/framework/src/test/java/org/tron/core/services/WalletApiTest.java +++ b/framework/src/test/java/org/tron/core/services/WalletApiTest.java @@ -12,9 +12,9 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.rules.Timeout; -import org.tron.common.ClassLevelAppContextFixture; 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.TronApplicationContext; import org.tron.common.utils.PublicMethod; 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 c57f7f42e2f..5c365eb3ef0 100644 --- a/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java +++ b/framework/src/test/java/org/tron/core/utils/TransactionRegisterTest.java @@ -14,8 +14,8 @@ import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 91e3b93fa96..6dcfb33a8b8 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -3,8 +3,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; import java.util.concurrent.TimeUnit; import javax.annotation.Resource; From 1f063c34e0c7fef8ef74fc4c80a8085ee8403b66 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 15:25:28 +0800 Subject: [PATCH 08/28] chore(config): remove /.dev/ from .gitignore Move to local .git/info/exclude instead. Co-Authored-By: Claude Sonnet 4.6 --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index 6587cb5b287..3917bb44679 100644 --- a/.gitignore +++ b/.gitignore @@ -57,4 +57,3 @@ Wallet /framework/propPath .cache -/.dev/ From 54e380216ef0ad77a2a3e1610c4ac1e04f66da7e Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 15:31:35 +0800 Subject: [PATCH 09/28] style(test): fix import order in SolidityNodeTest Co-Authored-By: Claude Sonnet 4.6 --- framework/src/test/java/org/tron/program/SolidityNodeTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 6dcfb33a8b8..2313e594566 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -2,8 +2,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import java.util.concurrent.TimeUnit; From 0c22d0f9170a544d0f14b0801540ecdfbd9d913a Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 15:45:47 +0800 Subject: [PATCH 10/28] test(framework): use assertSame for exception identity check in SolidityNodeTest Co-Authored-By: Claude Sonnet 4.6 --- framework/src/test/java/org/tron/program/SolidityNodeTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 2313e594566..782f934d686 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -1,6 +1,7 @@ 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; @@ -116,7 +117,7 @@ public void testAwaitShutdownStopsNodeWhenBlockedCallFails() { RuntimeException thrown = assertThrows(RuntimeException.class, () -> SolidityNode.awaitShutdown(app, node)); - assertEquals(expected, thrown); + assertSame(expected, thrown); InOrder inOrder = inOrder(app, node); inOrder.verify(app).blockUntilShutdown(); From 56f17fe2c87653836972db7edc697cf17623791e Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 16:21:24 +0800 Subject: [PATCH 11/28] fix(net): guard relay nodes in peer connection --- .../main/java/org/tron/core/net/peer/PeerConnection.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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..ebd4a3827ad 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(); @@ -166,7 +164,9 @@ public class PeerConnection { public void setChannel(Channel channel) { this.channel = channel; - if (relayNodes.stream().anyMatch(n -> n.getAddress().equals(channel.getInetAddress()))) { + List 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()); From 0e6bbbfec61f15e215276d06b690b65e7dd98f9d Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 17:22:34 +0800 Subject: [PATCH 12/28] test(framework,plugins): fix flaky tests in bandwidth, stats and db-move - BandWidthRuntimeTest: deploy contract before setDebug(true) to avoid CPU timeout triggered by debug mode during contract deployment - TronStatsManagerTest: capture P2pStats snapshot before invoking work() and compare against snapshot instead of hardcoded 0, preventing failures when another test starts the real P2pService with non-zero stats - DbMoveTest: add @After cleanup of output-directory-toolkit so LevelDB and RocksDB tests don't share the same relative destination path - PeerStatusCheckMockTest: replace 5-second sleep with mock executor; verify scheduleWithFixedDelay args and run the captured Runnable directly Co-Authored-By: Claude Sonnet 4.6 --- .../runtime/vm/BandWidthRuntimeTest.java | 7 ++++- .../net/peer/PeerStatusCheckMockTest.java | 27 ++++++++++++++----- .../net/services/TronStatsManagerTest.java | 16 ++++++++--- .../java/org/tron/plugins/DbMoveTest.java | 26 ++++++++++++++++++ 4 files changed, 65 insertions(+), 11 deletions(-) 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..6b8b138c3f3 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,10 @@ public void testSuccess() { @Test public void testSuccessNoBandd() { + boolean originalDebug = CommonParameter.getInstance().isDebug(); try { byte[] contractAddress = createContract(); + CommonParameter.getInstance().setDebug(true); TriggerSmartContract triggerContract = TvmTestUtils.createTriggerContract(contractAddress, "setCoin(uint256)", "50", false, 0, Commons.decodeFromBase58Check(TriggerOwnerTwoAddress)); @@ -185,6 +188,8 @@ public void testSuccessNoBandd() { balance); } catch (TronException e) { Assert.assertNotNull(e); + } finally { + CommonParameter.getInstance().setDebug(originalDebug); } } @@ -254,4 +259,4 @@ public void testMaxContractResultSize() { } Assert.assertEquals(2, maxSize); } -} \ No newline at end of file +} 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 c518e22280b..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,12 +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 @@ -15,17 +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; wait for at least one execution - 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(); - // Verify statusCheck() was invoked by the scheduler and the exception was handled gracefully - Mockito.verify(peerStatusCheck, Mockito.atLeastOnce()).statusCheck(); + 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/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/plugins/src/test/java/org/tron/plugins/DbMoveTest.java b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java index 6df17c4251c..ec4f0d545b0 100644 --- a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java +++ b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java @@ -5,6 +5,7 @@ import java.net.URL; import java.nio.file.Paths; import lombok.extern.slf4j.Slf4j; +import org.junit.After; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; @@ -17,6 +18,8 @@ @Slf4j public class DbMoveTest { + private static final String OUTPUT_DIRECTORY = "output-directory-toolkit"; + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -30,6 +33,29 @@ private void init(DbTool.DbType dbType, String path) throws IOException, RocksDB DbTool.getDB(path, TRANS, dbType).close(); } + @After + public void destroy() { + deleteDir(new File(OUTPUT_DIRECTORY)); + } + + /** + * 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(); + } + private static String getConfig(String config) { URL path = DbMoveTest.class.getClassLoader().getResource(config); return path == null ? null : path.getPath(); From 49e656aa8589ce4910bad5d08214834ac91cd590 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 8 Apr 2026 17:42:23 +0800 Subject: [PATCH 13/28] refactor(framework): promote relayNodes to instance field in PeerConnection Extract relayNodes from a local variable inside setChannel() to a lazy- initialized instance field. setChannel() now only fetches from Args when the field is still null, so tests can pre-inject a custom list via reflection before calling setChannel(). This restores testability of PeerManagerTest without touching the test itself. Co-Authored-By: Claude Sonnet 4.6 --- .../main/java/org/tron/core/net/peer/PeerConnection.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) 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 ebd4a3827ad..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 @@ -161,10 +161,14 @@ 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; - List relayNodes = Args.getInstance().getFastForwardNodes(); + if (this.relayNodes == null) { + this.relayNodes = Args.getInstance().getFastForwardNodes(); + } if (relayNodes != null && relayNodes.stream().anyMatch(n -> n.getAddress().equals(channel.getInetAddress()))) { this.isRelayPeer = true; From 4506ec96cb13c24544fe51407296fda0e444cdf5 Mon Sep 17 00:00:00 2001 From: Asuka Date: Tue, 31 Mar 2026 12:05:06 +0800 Subject: [PATCH 14/28] refactor(tvm): optimize energy cost calculation for vote witness opcode Use BigInteger for memory size computation to improve precision and add unit tests. Co-Authored-By: Claude Opus 4.6 --- .../java/org/tron/common/runtime/vm/VoteWitnessCost3Test.java | 2 -- 1 file changed, 2 deletions(-) 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); From d12d6dfdf8b79fae0787b01cd90d26ce3ddf918c Mon Sep 17 00:00:00 2001 From: GrapeS Date: Mon, 13 Apr 2026 13:08:40 +0800 Subject: [PATCH 15/28] fix(framework): replace while(true) with while(flag) in SolidityNode getBlockByNum() and getLastSolidityBlockNum() used while(true) which ignores the shutdown flag. If either method is blocked retrying on network errors, shutdown() cannot interrupt the thread, causing ExecutorServiceManager.shutdownAndAwaitTermination to time out. Co-Authored-By: Claude Sonnet 4.6 --- .../java/org/tron/program/SolidityNode.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index de0bdaea1de..db7972bd4af 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -81,15 +81,15 @@ public static void start() { 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(); - } - } + 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 { @@ -161,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); @@ -182,7 +182,7 @@ private Block getBlockByNum(long blockNum) { } private long getLastSolidityBlockNum() { - while (true) { + while (flag) { try { long time = System.currentTimeMillis(); long blockNum = databaseGrpcClient.getDynamicProperties().getLastSolidityBlockNum(); From 962bef31821ad8306302c20672b8fd3441609818 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Mon, 13 Apr 2026 13:09:02 +0800 Subject: [PATCH 16/28] fix(framework): add null/0 return after while(flag) loops in SolidityNode Compiler requires explicit return values when while(flag) can exit without entering the loop body (e.g. during shutdown). Co-Authored-By: Claude Sonnet 4.6 --- framework/src/main/java/org/tron/program/SolidityNode.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index db7972bd4af..f1c5bab0dce 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -179,6 +179,7 @@ private Block getBlockByNum(long blockNum) { sleep(exceptionSleepTime); } } + return null; } private long getLastSolidityBlockNum() { @@ -195,6 +196,7 @@ private long getLastSolidityBlockNum() { sleep(exceptionSleepTime); } } + return 0; } public void sleep(long time) { From c91b8b1a355fa1dad8dbeee2b9cde521fd9003ae Mon Sep 17 00:00:00 2001 From: GrapeS Date: Mon, 13 Apr 2026 14:03:19 +0800 Subject: [PATCH 17/28] fix(test): add comments --- .../java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java | 3 +++ 1 file changed, 3 insertions(+) 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 6b8b138c3f3..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 @@ -157,6 +157,9 @@ 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, From b6700a06b834fd6f54491649ee167f745203a521 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Tue, 14 Apr 2026 09:58:51 +0800 Subject: [PATCH 18/28] test(framework): address PR review comments on test code quality - Remove dead moreThanFrozenNumber test in FreezeBalanceV2ActuatorTest (error message no longer exists in production code) - Remove unnecessary try/catch around addAssetV2 in AccountAssetStoreTest (method declares no checked exceptions) - Replace try/catch pattern with Assert.assertThrows in FetchInvDataMsgHandlerTest Co-Authored-By: Claude Sonnet 4.6 --- .../actuator/FreezeBalanceV2ActuatorTest.java | 27 ------------------- .../tron/core/db/AccountAssetStoreTest.java | 6 +---- .../FetchInvDataMsgHandlerTest.java | 22 ++++++--------- 3 files changed, 9 insertions(+), 46 deletions(-) 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/db/AccountAssetStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java index 24475f3c7f7..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) { - Assert.fail(e.getMessage()); - } + 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/net/messagehandler/FetchInvDataMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java index f8677b6bc04..5022ca4233e 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,23 +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); - Assert.fail("Expected exception was not thrown: maxBlockNum: 1000, blockNum: 10000"); - } catch (Exception e) { - Assert.assertEquals("maxBlockNum: 1000, blockNum: 10000", e.getMessage()); - } + 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); - Assert.fail("Expected exception was not thrown: minBlockNum: 16000, blockNum: 10000"); - } catch (Exception e) { - Assert.assertEquals("minBlockNum: 16000, blockNum: 10000", e.getMessage()); - } + Exception e2 = Assert.assertThrows(Exception.class, + () -> fetchInvDataMsgHandler.processMessage(peer, msg)); + Assert.assertEquals("minBlockNum: 16000, blockNum: 10000", e2.getMessage()); } @Test From 6731f1b31a850bb617de7e6c16f724504dfef0f6 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Tue, 14 Apr 2026 15:43:12 +0800 Subject: [PATCH 19/28] fix: use Assert.assertThrows to replace try/catch --- .../common/backup/socket/BackupServer.java | 6 +- .../tron/common/backup/BackupServerTest.java | 4 +- .../java/org/tron/core/ShieldWalletTest.java | 28 +- .../test/java/org/tron/core/WalletTest.java | 25 +- .../MarketCancelOrderActuatorTest.java | 36 +- .../UnDelegateResourceActuatorTest.java | 60 +- .../actuator/UnfreezeBalanceActuatorTest.java | 9 +- .../actuator/VoteWitnessActuatorTest.java | 16 +- .../core/actuator/utils/ProposalUtilTest.java | 724 +++++++----------- .../core/capsule/utils/MerkleTreeTest.java | 9 +- .../tron/core/capsule/utils/RLPListTest.java | 8 +- .../org/tron/core/db/AccountStoreTest.java | 9 +- .../java/org/tron/core/db/ManagerTest.java | 18 +- .../tron/core/event/BlockEventCacheTest.java | 18 +- .../tron/core/event/BlockEventGetTest.java | 86 +-- .../tron/core/jsonrpc/JsonrpcServiceTest.java | 354 ++++----- .../java/org/tron/core/net/MessageTest.java | 13 +- .../test/java/org/tron/core/net/NodeTest.java | 24 +- .../FetchInvDataMsgHandlerTest.java | 19 +- .../org/tron/keystore/CredentialsTest.java | 13 +- 20 files changed, 570 insertions(+), 909 deletions(-) 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/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/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/MarketCancelOrderActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java index d2ec8c30994..4966ef67987 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java @@ -188,12 +188,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()); } /** @@ -208,12 +205,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()); } /** @@ -227,12 +221,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()); } /** @@ -261,12 +252,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 247a52e648f..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.fail("Expected IndexOutOfBoundsException for empty hash list"); - } 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/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/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/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/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/net/MessageTest.java b/framework/src/test/java/org/tron/core/net/MessageTest.java index a2264545dc0..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,8 +19,7 @@ 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(), @@ -30,16 +29,6 @@ public void test1() throws Exception { } } - 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(); - } - @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 5022ca4233e..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 @@ -144,17 +144,12 @@ public void testRateLimiter() { Mockito.when(peer.getP2pRateLimiter()).thenReturn(p2pRateLimiter); FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler(); - try { - fetchInvDataMsgHandler.processMessage(peer, msg); - Assert.fail("Expected exception was not thrown: fetch too many blocks, size:101"); - } catch (Exception e) { - Assert.assertEquals("fetch too many blocks, size:101", e.getMessage()); - } - try { - fetchInvDataMsgHandler.processMessage(peer, msg); - Assert.fail("Expected rate limit exception was not thrown"); - } 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/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java index 97cb5d54139..58c5c905b15 100644 --- a/framework/src/test/java/org/tron/keystore/CredentialsTest.java +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -33,14 +33,11 @@ public void testCreate() { @Test public void testCreateFromSM2() { - try { - Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffffffffff"))); - Assert.fail("Expected IllegalArgumentException"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - } + Exception e = Assert.assertThrows(Exception.class, + () -> Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffffffffff")))); + Assert.assertTrue(e instanceof IllegalArgumentException); } @Test From b6ec6e1e09d16e3e480473be6814818137f155fb Mon Sep 17 00:00:00 2001 From: GrapeS Date: Tue, 14 Apr 2026 16:02:24 +0800 Subject: [PATCH 20/28] fix: pr review --- .../core/witness/ProposalControllerTest.java | 41 ++++++------------- 1 file changed, 13 insertions(+), 28 deletions(-) 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 94e50b410a0..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) { - Assert.fail(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) { - Assert.fail(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) { - Assert.fail(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) { - Assert.fail(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)); } From dbc6abacae20b994005000e849d88e9d9327fbb9 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Thu, 16 Apr 2026 16:55:29 +0800 Subject: [PATCH 21/28] test(framework): replace Assert.fail with throws Exception in test methods Co-Authored-By: Claude Sonnet 4.6 --- .../org/tron/common/utils/PropUtilTest.java | 17 ++----- .../java/org/tron/core/db/BlockStoreTest.java | 47 +++++++------------ .../org/tron/core/db2/SnapshotImplTest.java | 18 +++---- 3 files changed, 27 insertions(+), 55 deletions(-) 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 330d97bd51c..bc4d15a4df7 100644 --- a/framework/src/test/java/org/tron/common/utils/PropUtilTest.java +++ b/framework/src/test/java/org/tron/common/utils/PropUtilTest.java @@ -1,21 +1,16 @@ package org.tron.common.utils; import java.io.File; -import java.io.IOException; import org.junit.Assert; import org.junit.Test; public class PropUtilTest { @Test - public void testWriteProperty() { + public void testWriteProperty() throws Exception { String filename = "test_prop.properties"; File file = new File(filename); - try { - file.createNewFile(); - } catch (IOException e) { - Assert.fail(e.getMessage()); - } + file.createNewFile(); PropUtil.writeProperty(filename, "key", "value"); Assert.assertTrue("value".equals(PropUtil.readProperty(filename, "key"))); PropUtil.writeProperty(filename, "key", "value2"); @@ -24,14 +19,10 @@ public void testWriteProperty() { } @Test - public void testReadProperty() { + public void testReadProperty() throws Exception { String filename = "test_prop.properties"; File file = new File(filename); - try { - file.createNewFile(); - } catch (IOException e) { - Assert.fail(e.getMessage()); - } + file.createNewFile(); PropUtil.writeProperty(filename, "key", "value"); Assert.assertTrue("value".equals(PropUtil.readProperty(filename, "key"))); file.delete(); 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 fd408281ab2..b85a6312278 100644 --- a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java @@ -10,8 +10,6 @@ import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.args.Args; -import org.tron.core.exception.BadItemException; -import org.tron.core.exception.ItemNotFoundException; @Slf4j @@ -35,56 +33,43 @@ public void testCreateBlockStore() { } @Test - public void testPut() { + public void testPut() throws Exception { long number = 1; BlockCapsule blockCapsule = getBlockCapsule(number); byte[] blockId = blockCapsule.getBlockId().getBytes(); blockStore.put(blockId, blockCapsule); - try { - BlockCapsule blockCapsule1 = blockStore.get(blockId); - Assert.assertNotNull(blockCapsule1); - Assert.assertEquals(number, blockCapsule1.getNum()); - } catch (ItemNotFoundException | BadItemException e) { - Assert.fail(e.getMessage()); - } + BlockCapsule blockCapsule1 = blockStore.get(blockId); + Assert.assertNotNull(blockCapsule1); + Assert.assertEquals(number, blockCapsule1.getNum()); } @Test - public void testGet() { + public void testGet() throws Exception { long number = 2; BlockCapsule blockCapsule = getBlockCapsule(number); byte[] blockId = blockCapsule.getBlockId().getBytes(); blockStore.put(blockId, blockCapsule); - try { - boolean has = blockStore.has(blockId); - Assert.assertTrue(has); - BlockCapsule blockCapsule1 = blockStore.get(blockId); - - Assert.assertEquals(number, blockCapsule1.getNum()); - } catch (ItemNotFoundException | BadItemException e) { - Assert.fail(e.getMessage()); - } + boolean has = blockStore.has(blockId); + Assert.assertTrue(has); + BlockCapsule blockCapsule1 = blockStore.get(blockId); + Assert.assertEquals(number, blockCapsule1.getNum()); } @Test - public void testDelete() { + public void testDelete() throws Exception { long number = 1; BlockCapsule blockCapsule = getBlockCapsule(number); byte[] blockId = blockCapsule.getBlockId().getBytes(); blockStore.put(blockId, blockCapsule); - try { - BlockCapsule blockCapsule1 = blockStore.get(blockId); - Assert.assertNotNull(blockCapsule1); - Assert.assertEquals(number, blockCapsule1.getNum()); + BlockCapsule blockCapsule1 = blockStore.get(blockId); + Assert.assertNotNull(blockCapsule1); + Assert.assertEquals(number, blockCapsule1.getNum()); - blockStore.delete(blockId); - BlockCapsule blockCapsule2 = blockStore.getUnchecked(blockId); - Assert.assertNull(blockCapsule2); - } catch (ItemNotFoundException | BadItemException e) { - Assert.fail(e.getMessage()); - } + blockStore.delete(blockId); + BlockCapsule blockCapsule2 = blockStore.getUnchecked(blockId); + Assert.assertNull(blockCapsule2); } } 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 4948f3d935c..3ee61065d1f 100644 --- a/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java +++ b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java @@ -38,7 +38,7 @@ protected void beforeDestroy() { * from: get key1 or key2, traverse 0 times */ @Test - public void testMergeRoot() { + public void testMergeRoot() throws Exception { // linklist is: from -> root SnapshotRoot root = new SnapshotRoot(tronDatabase.getDb()); //root.setOptimized(true); @@ -68,7 +68,7 @@ public void testMergeRoot() { * */ @Test - public void testMergeAhead() { + public void testMergeAhead() throws Exception { // linklist is: from2 -> from -> root SnapshotRoot root = new SnapshotRoot(tronDatabase.getDb()); @@ -136,7 +136,7 @@ public void testMergeAhead() { * from2: key1=>value1, key2=>value2, key3=>value32, key4=>value4 */ @Test - public void testMergeOverride() { + public void testMergeOverride() throws Exception { // linklist is: from2 -> from -> root SnapshotRoot root = new SnapshotRoot(tronDatabase.getDb()); SnapshotImpl from = getSnapshotImplIns(root); @@ -165,15 +165,11 @@ public void testMergeOverride() { * The constructor of SnapshotImpl is not public * so reflection is used to construct the object here. */ - private SnapshotImpl getSnapshotImplIns(Snapshot snapshot) { + private SnapshotImpl getSnapshotImplIns(Snapshot snapshot) throws Exception { Class clazz = SnapshotImpl.class; - try { - Constructor constructor = clazz.getDeclaredConstructor(Snapshot.class); - constructor.setAccessible(true); - return (SnapshotImpl) constructor.newInstance(snapshot); - } catch (Exception e) { - throw new AssertionError(e); - } + Constructor constructor = clazz.getDeclaredConstructor(Snapshot.class); + constructor.setAccessible(true); + return (SnapshotImpl) constructor.newInstance(snapshot); } } From 233e1b646e5fd21efcafc0a602f5383c9f1e5e2f Mon Sep 17 00:00:00 2001 From: GrapeS Date: Wed, 22 Apr 2026 12:06:33 +0800 Subject: [PATCH 22/28] test(framework): address PR review nits in BlockEventGetTest and PeerStatusCheckMockTest - BlockEventGetTest: reset EventPluginLoader.filterQuery to null in @Before to prevent FilterQueryTest's leftover state from suppressing processTrigger coverage when tests share the same Gradle forkEvery JVM batch - PeerStatusCheckMockTest: remove dead Assert.assertNotNull(peerStatusCheck) assertion and its now-unused import; the local variable is trivially non-null Co-Authored-By: Claude Sonnet 4.6 --- .../src/test/java/org/tron/core/event/BlockEventGetTest.java | 3 +++ .../java/org/tron/core/net/peer/PeerStatusCheckMockTest.java | 2 -- 2 files changed, 3 insertions(+), 2 deletions(-) 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 227e539aa37..6ea8a53670b 100644 --- a/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java +++ b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java @@ -112,6 +112,9 @@ public void before() throws IOException { // 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; + // Reset filterQuery so FilterQueryTest's leftover state does not suppress processTrigger + // coverage when tests share the same Gradle forkEvery JVM batch. + EventPluginLoader.getInstance().setFilterQuery(null); DynamicPropertiesStore dps = dbManager.getDynamicPropertiesStore(); dps.saveAllowTvmTransferTrc10(1); 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 fc0718e1d2d..d2ee4be5b87 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 @@ -9,7 +9,6 @@ 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; @@ -40,7 +39,6 @@ public void testInitException() { scheduledTask.run(); Mockito.verify(peerStatusCheck).statusCheck(); - Assert.assertNotNull(peerStatusCheck); } } From b33b03ca2d4e565e0e71c150c2cbf922af51a148 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Thu, 23 Apr 2026 11:20:28 +0800 Subject: [PATCH 23/28] refactor(framework): address shutdown correctness issues from PR review - SolidityNode: signal both executor pools before awaiting either so they drain concurrently, halving worst-case shutdown latency - BackupServer: remove dead restart loop and shutdown flag, fix backupManager.stop() ordering (after ingress closed), drop redundant channel.close().await() in favour of ESM as single sync barrier - NativeMessageQueueTest: replace manual shutdownNow()+2s await with ExecutorServiceManager.shutdownAndAwaitTermination to prevent zmq subscriber thread leaking across test runs Co-Authored-By: Claude Sonnet 4.6 --- .../common/backup/socket/BackupServer.java | 63 +++++++------------ .../java/org/tron/program/SolidityNode.java | 3 + .../logsfilter/NativeMessageQueueTest.java | 15 ++--- 3 files changed, 28 insertions(+), 53 deletions(-) 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 5cdb35fa945..1d44b37d69a 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 @@ -8,7 +8,6 @@ import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -29,8 +28,6 @@ public class BackupServer implements AutoCloseable { private volatile Channel channel; - private volatile boolean shutdown = false; - private final String name = "BackupServer"; private ExecutorService executor; @@ -55,39 +52,26 @@ public void initServer() { private void start() throws Exception { NioEventLoopGroup group = new NioEventLoopGroup(1); try { - while (!shutdown) { - Bootstrap b = new Bootstrap(); - b.group(group) - .channel(NioDatagramChannel.class) - .handler(new ChannelInitializer() { - @Override - public void initChannel(NioDatagramChannel ch) - throws Exception { - ch.pipeline().addLast(TrafficStats.udp); - ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); - ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); - ch.pipeline().addLast(new PacketDecoder()); - MessageHandler messageHandler = new MessageHandler(ch, backupManager); - backupManager.setMessageHandler(messageHandler); - ch.pipeline().addLast(messageHandler); - } - }); - - channel = b.bind(port).sync().channel(); - - logger.info("Backup server started, bind port {}", port); + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioDatagramChannel.class) + .handler(new ChannelInitializer() { + @Override + public void initChannel(NioDatagramChannel ch) { + ch.pipeline().addLast(TrafficStats.udp); + ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); + ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); + ch.pipeline().addLast(new PacketDecoder()); + MessageHandler messageHandler = new MessageHandler(ch, backupManager); + backupManager.setMessageHandler(messageHandler); + ch.pipeline().addLast(messageHandler); + } + }); - // 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"); - break; - } - logger.warn("Restart backup server ..."); - } + channel = b.bind(port).sync().channel(); + logger.info("Backup server started, bind port {}", port); + channel.closeFuture().sync(); + logger.info("Shutdown backup BackupServer"); } catch (Exception e) { logger.error("Start backup server with port {} failed.", port, e); } finally { @@ -98,16 +82,11 @@ public void initChannel(NioDatagramChannel ch) @Override public void close() { logger.info("Closing backup server..."); - shutdown = true; - backupManager.stop(); if (channel != null) { - try { - channel.close().await(10, TimeUnit.SECONDS); - } catch (Exception e) { - logger.warn("Closing backup server failed.", e); - } + channel.close(); // fire-and-forget: unblocks closeFuture().sync() in start() } ExecutorServiceManager.shutdownAndAwaitTermination(executor, name); + backupManager.stop(); // stop after ingress is fully closed logger.info("Backup server closed."); } } diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index f1c5bab0dce..297c337eccb 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -108,6 +108,9 @@ private void run() { public void shutdown() { flag = false; + // Signal both pools before awaiting either so they drain concurrently + getBlockEs.shutdown(); + processBlockEs.shutdown(); ExecutorServiceManager.shutdownAndAwaitTermination(getBlockEs, "solid-get-block"); ExecutorServiceManager.shutdownAndAwaitTermination(processBlockEs, "solid-process-block"); } 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 a71b64b0a6d..5219654977b 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,6 @@ 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; @@ -18,18 +17,12 @@ public class NativeMessageQueueTest { public String topic = "testTopic"; private ExecutorService subscriberExecutor; + private final String zmqSubscriber = "zmq-subscriber"; @After public void tearDown() { - if (subscriberExecutor != null) { - subscriberExecutor.shutdownNow(); - try { - subscriberExecutor.awaitTermination(2, TimeUnit.SECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - subscriberExecutor = null; - } + ExecutorServiceManager.shutdownAndAwaitTermination(subscriberExecutor, zmqSubscriber); + subscriberExecutor = null; } @Test @@ -73,7 +66,7 @@ public void publishTrigger() { } public void startSubscribeThread() { - subscriberExecutor = ExecutorServiceManager.newSingleThreadExecutor("zmq-subscriber"); + subscriberExecutor = ExecutorServiceManager.newSingleThreadExecutor(zmqSubscriber); subscriberExecutor.execute(() -> { try (ZContext context = new ZContext()) { ZMQ.Socket subscriber = context.createSocket(SocketType.SUB); From 20b3a06d1f4df4d33ca97eb95780c9c8136b39dd Mon Sep 17 00:00:00 2001 From: GrapeS Date: Thu, 23 Apr 2026 11:29:11 +0800 Subject: [PATCH 24/28] refactor(framework): address PR review nits from bladehan1 - PeerConnection: make relayNodes volatile and document lazy-init rationale; remove unused @Getter (no external callers) - ConcurrentHashMapTest: use daemon executor to avoid holding JVM open on abrupt exit - BackupServerTest: add comment explaining 90s globalTimeout budget - SolidityNode: mark awaitShutdown @VisibleForTesting Co-Authored-By: Claude Sonnet 4.6 --- .../main/java/org/tron/core/net/peer/PeerConnection.java | 6 ++++-- framework/src/main/java/org/tron/program/SolidityNode.java | 2 ++ .../test/java/org/tron/common/backup/BackupServerTest.java | 2 ++ .../java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) 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 ef2c7d5983a..83d5734be76 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 @@ -161,8 +161,10 @@ public class PeerConnection { private volatile boolean needSyncFromUs = true; @Getter private P2pRateLimiter p2pRateLimiter = new P2pRateLimiter(); - @Getter - private List relayNodes; + // Lazily initialised in setChannel() because Args may not be fully wired at class-load time. + // volatile ensures the write is visible to readers without requiring setChannel() to be called + // under a lock held by the caller. + private volatile List relayNodes; public void setChannel(Channel channel) { this.channel = channel; diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index 297c337eccb..6ffa3b3ce92 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -2,6 +2,7 @@ import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import com.google.common.annotations.VisibleForTesting; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; @@ -81,6 +82,7 @@ public static void start() { awaitShutdown(appT, node); } + @VisibleForTesting static void awaitShutdown(Application appT, SolidityNode node) { try { appT.blockUntilShutdown(); 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 f9795587032..ede872fa6e1 100644 --- a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java +++ b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java @@ -20,6 +20,8 @@ public class BackupServerTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + // 90s = up to 60s for ExecutorServiceManager.shutdownAndAwaitTermination inside + // BackupServer.close() (called by @After tearDown) + 30s headroom for test body and startup. @Rule public Timeout globalTimeout = Timeout.seconds(90); private BackupServer backupServer; 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 07eb6d7da1f..2cdcaaf7a53 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java @@ -61,7 +61,7 @@ public void testHandleBlockHash() { Assert.fail("Interrupted during test setup: " + e.getMessage()); } - ExecutorService executor = ExecutorServiceManager.newFixedThreadPool(EXECUTOR_NAME, 4); + ExecutorService executor = ExecutorServiceManager.newFixedThreadPool(EXECUTOR_NAME, 4, true); try { Future putTask = executor.submit(() -> { From 214363ff2a5d3a9ab1eff04b7b59c2fc00475371 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Thu, 23 Apr 2026 17:03:21 +0800 Subject: [PATCH 25/28] refactor(net): revert relayNodes to local variable in setChannel Per reviewer feedback, the lazy instance field was added to support test injection via reflection. Use a local variable instead (matching the post-fix(net) shape) and set CommonParameter.fastForwardNodes directly in tests that need to control the relay node list. Co-Authored-By: Claude Sonnet 4.6 --- .../org/tron/core/net/peer/PeerConnection.java | 9 +-------- .../org/tron/core/net/peer/PeerConnectionTest.java | 14 +++----------- 2 files changed, 4 insertions(+), 19 deletions(-) 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 83d5734be76..75265809612 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 @@ -161,16 +161,9 @@ public class PeerConnection { private volatile boolean needSyncFromUs = true; @Getter private P2pRateLimiter p2pRateLimiter = new P2pRateLimiter(); - // Lazily initialised in setChannel() because Args may not be fully wired at class-load time. - // volatile ensures the write is visible to readers without requiring setChannel() to be called - // under a lock held by the caller. - private volatile List relayNodes; - public void setChannel(Channel channel) { this.channel = channel; - if (this.relayNodes == null) { - this.relayNodes = Args.getInstance().getFastForwardNodes(); - } + List relayNodes = Args.getInstance().getFastForwardNodes(); if (relayNodes != null && relayNodes.stream().anyMatch(n -> n.getAddress().equals(channel.getInetAddress()))) { this.isRelayPeer = true; diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java index 649e5eb0875..5821bcc380d 100644 --- a/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java +++ b/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java @@ -195,7 +195,7 @@ public void testSetChannel() { ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); List relayNodes = new ArrayList<>(); - ReflectUtils.setFieldValue(peerConnection, "relayNodes", relayNodes); + CommonParameter.getInstance().fastForwardNodes = relayNodes; peerConnection.setChannel(c1); Assert.assertTrue(!peerConnection.isRelayPeer()); @@ -203,6 +203,8 @@ public void testSetChannel() { relayNodes.add(inetSocketAddress); peerConnection.setChannel(c1); Assert.assertTrue(peerConnection.isRelayPeer()); + + CommonParameter.getInstance().fastForwardNodes = new ArrayList<>(); } @Test @@ -234,15 +236,12 @@ public void testCheckAndPutAdvInvRequest() { @Test public void testEquals() { - List relayNodes = new ArrayList<>(); - PeerConnection p1 = new PeerConnection(); InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.2", 10001); Channel c1 = new Channel(); ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); - ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); p1.setChannel(c1); PeerConnection p2 = new PeerConnection(); @@ -251,7 +250,6 @@ public void testEquals() { Channel c2 = new Channel(); ReflectUtils.setFieldValue(c2, "inetSocketAddress", inetSocketAddress2); ReflectUtils.setFieldValue(c2, "inetAddress", inetSocketAddress2.getAddress()); - ReflectUtils.setFieldValue(p2, "relayNodes", relayNodes); p2.setChannel(c2); PeerConnection p3 = new PeerConnection(); @@ -260,7 +258,6 @@ public void testEquals() { Channel c3 = new Channel(); ReflectUtils.setFieldValue(c3, "inetSocketAddress", inetSocketAddress3); ReflectUtils.setFieldValue(c3, "inetAddress", inetSocketAddress3.getAddress()); - ReflectUtils.setFieldValue(p3, "relayNodes", relayNodes); p3.setChannel(c3); Assert.assertTrue(p1.equals(p1)); @@ -270,15 +267,12 @@ public void testEquals() { @Test public void testHashCode() { - List relayNodes = new ArrayList<>(); - PeerConnection p1 = new PeerConnection(); InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.2", 10001); Channel c1 = new Channel(); ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); - ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); p1.setChannel(c1); PeerConnection p2 = new PeerConnection(); @@ -287,7 +281,6 @@ public void testHashCode() { Channel c2 = new Channel(); ReflectUtils.setFieldValue(c2, "inetSocketAddress", inetSocketAddress2); ReflectUtils.setFieldValue(c2, "inetAddress", inetSocketAddress2.getAddress()); - ReflectUtils.setFieldValue(p2, "relayNodes", relayNodes); p2.setChannel(c2); PeerConnection p3 = new PeerConnection(); @@ -296,7 +289,6 @@ public void testHashCode() { Channel c3 = new Channel(); ReflectUtils.setFieldValue(c3, "inetSocketAddress", inetSocketAddress3); ReflectUtils.setFieldValue(c3, "inetAddress", inetSocketAddress3.getAddress()); - ReflectUtils.setFieldValue(p3, "relayNodes", relayNodes); p3.setChannel(c3); Assert.assertTrue(p1.hashCode() != p2.hashCode()); From a63d603bd465464a1ccd49c2aa7dab345a3799bf Mon Sep 17 00:00:00 2001 From: GrapeS Date: Fri, 24 Apr 2026 15:04:15 +0800 Subject: [PATCH 26/28] style(net): add empty line before setChannel method in PeerConnection Co-Authored-By: Claude Sonnet 4.6 --- .../src/main/java/org/tron/core/net/peer/PeerConnection.java | 1 + 1 file changed, 1 insertion(+) 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 75265809612..ebd4a3827ad 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 @@ -161,6 +161,7 @@ public class PeerConnection { private volatile boolean needSyncFromUs = true; @Getter private P2pRateLimiter p2pRateLimiter = new P2pRateLimiter(); + public void setChannel(Channel channel) { this.channel = channel; List relayNodes = Args.getInstance().getFastForwardNodes(); From b7f4c32f007336372c4da8a2b321264cdeaee7b2 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Fri, 24 Apr 2026 15:19:07 +0800 Subject: [PATCH 27/28] fix(backup): restore restart loop, fix channel visibility race only Revert the structural refactor of BackupServer to keep the original while(!shutdown) self-healing design. Apply only the minimal fix for the race condition where close() could be called before channel was assigned after bind(): - make channel volatile so close() always sees the latest reference - add shutdown check after bind() to avoid blocking on closeFuture() when shutdown was already set during the bind call Co-Authored-By: Claude Sonnet 4.6 --- .../common/backup/socket/BackupServer.java | 65 +++++++++++++------ .../tron/common/backup/BackupServerTest.java | 4 +- 2 files changed, 46 insertions(+), 23 deletions(-) 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 1d44b37d69a..59a46fcb495 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 @@ -8,6 +8,7 @@ import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -28,6 +29,8 @@ public class BackupServer implements AutoCloseable { private volatile Channel channel; + private volatile boolean shutdown = false; + private final String name = "BackupServer"; private ExecutorService executor; @@ -52,26 +55,41 @@ public void initServer() { private void start() throws Exception { NioEventLoopGroup group = new NioEventLoopGroup(1); try { - Bootstrap b = new Bootstrap(); - b.group(group) - .channel(NioDatagramChannel.class) - .handler(new ChannelInitializer() { - @Override - public void initChannel(NioDatagramChannel ch) { - ch.pipeline().addLast(TrafficStats.udp); - ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); - ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); - ch.pipeline().addLast(new PacketDecoder()); - MessageHandler messageHandler = new MessageHandler(ch, backupManager); - backupManager.setMessageHandler(messageHandler); - ch.pipeline().addLast(messageHandler); - } - }); + while (!shutdown) { + Bootstrap b = new Bootstrap(); + b.group(group) + .channel(NioDatagramChannel.class) + .handler(new ChannelInitializer() { + @Override + public void initChannel(NioDatagramChannel ch) + throws Exception { + ch.pipeline().addLast(TrafficStats.udp); + ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); + ch.pipeline().addLast(new ProtobufVarint32FrameDecoder()); + ch.pipeline().addLast(new PacketDecoder()); + MessageHandler messageHandler = new MessageHandler(ch, backupManager); + backupManager.setMessageHandler(messageHandler); + ch.pipeline().addLast(messageHandler); + } + }); + + channel = b.bind(port).sync().channel(); + + logger.info("Backup server started, bind port {}", port); - channel = b.bind(port).sync().channel(); - logger.info("Backup server started, bind port {}", port); - channel.closeFuture().sync(); - logger.info("Shutdown backup BackupServer"); + // If close() was called while bind() was in progress, channel was not yet visible; + // check again before blocking on closeFuture to avoid hanging indefinitely. + if (shutdown) { + channel.close(); + break; + } + channel.closeFuture().sync(); + if (shutdown) { + logger.info("Shutdown backup BackupServer"); + break; + } + logger.warn("Restart backup server ..."); + } } catch (Exception e) { logger.error("Start backup server with port {} failed.", port, e); } finally { @@ -82,11 +100,16 @@ public void initChannel(NioDatagramChannel ch) { @Override public void close() { logger.info("Closing backup server..."); + shutdown = true; + backupManager.stop(); if (channel != null) { - channel.close(); // fire-and-forget: unblocks closeFuture().sync() in start() + try { + channel.close().await(10, TimeUnit.SECONDS); + } catch (Exception e) { + logger.warn("Closing backup server failed.", e); + } } ExecutorServiceManager.shutdownAndAwaitTermination(executor, name); - backupManager.stop(); // stop after ingress is fully closed logger.info("Backup server closed."); } } 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 ede872fa6e1..7a9dec11515 100644 --- a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java +++ b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java @@ -20,8 +20,8 @@ public class BackupServerTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - // 90s = up to 60s for ExecutorServiceManager.shutdownAndAwaitTermination inside - // BackupServer.close() (called by @After tearDown) + 30s headroom for test body and startup. + // 90s: close() calls channel.close().await(10s) then ESM.shutdownAndAwaitTermination (up to 60s), + // plus 20s headroom for server startup and test body. @Rule public Timeout globalTimeout = Timeout.seconds(90); private BackupServer backupServer; From 35bc7b176ee6c3049a3219f2917356a254742de4 Mon Sep 17 00:00:00 2001 From: GrapeS Date: Fri, 24 Apr 2026 16:34:11 +0800 Subject: [PATCH 28/28] fix(test): remove stale relayNodes field injection in PeerManagerTest The relayNodes instance field was removed from PeerConnection (reverted to local variable in setChannel()), so ReflectUtils.setFieldValue calls targeting that field caused NPE. Remove the field declaration and all injection lines. Co-Authored-By: Claude Sonnet 4.6 --- .../java/org/tron/core/net/peer/PeerManagerTest.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java index ee409a8ab04..513e9e4bcae 100644 --- a/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java +++ b/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java @@ -21,7 +21,6 @@ import org.tron.p2p.connection.Channel; public class PeerManagerTest { - List relayNodes = new ArrayList<>(); @BeforeClass public static void initArgs() { @@ -54,7 +53,7 @@ public void testAdd() throws Exception { Channel c1 = new Channel(); ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); - ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); ApplicationContext ctx = mock(ApplicationContext.class); @@ -79,7 +78,7 @@ public void testRemove() throws Exception { Channel c1 = new Channel(); ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); - ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); ApplicationContext ctx = mock(ApplicationContext.class); @@ -105,7 +104,7 @@ public void testGetPeerConnection() throws Exception { Channel c1 = new Channel(); ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); - ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); ApplicationContext ctx = mock(ApplicationContext.class); @@ -128,7 +127,7 @@ public void testGetPeers() throws Exception { Channel c1 = new Channel(); ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); - ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); ApplicationContext ctx = mock(ApplicationContext.class); @@ -146,7 +145,7 @@ public void testGetPeers() throws Exception { Channel c2 = new Channel(); ReflectUtils.setFieldValue(c2, "inetSocketAddress", inetSocketAddress2); ReflectUtils.setFieldValue(c2, "inetAddress", inetSocketAddress2.getAddress()); - ReflectUtils.setFieldValue(p2, "relayNodes", relayNodes); + p2.setChannel(c2); ApplicationContext ctx2 = mock(ApplicationContext.class);