diff --git a/framework/src/test/java/org/tron/common/EntityTest.java b/framework/src/test/java/org/tron/common/EntityTest.java new file mode 100644 index 00000000000..483475a453b --- /dev/null +++ b/framework/src/test/java/org/tron/common/EntityTest.java @@ -0,0 +1,67 @@ +package org.tron.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Lists; +import java.util.HashMap; +import org.apache.commons.collections4.CollectionUtils; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.entity.NodeInfo; +import org.tron.common.entity.NodeInfo.MachineInfo; +import org.tron.common.entity.NodeInfo.MachineInfo.DeadLockThreadInfo; + +public class EntityTest { + + private final MachineInfo machineInfo = new MachineInfo(); + private final DeadLockThreadInfo deadLockThreadInfo = new DeadLockThreadInfo(); + + @Before + public void setup() { + deadLockThreadInfo.setName("name"); + deadLockThreadInfo.setLockName("lockName"); + deadLockThreadInfo.setLockOwner("lockOwner"); + deadLockThreadInfo.setState("state"); + deadLockThreadInfo.setStackTrace("stackTrace"); + deadLockThreadInfo.setWaitTime(0L); + deadLockThreadInfo.setBlockTime(0L); + machineInfo.setDeadLockThreadInfoList(Lists.newArrayList(deadLockThreadInfo)); + machineInfo.setJavaVersion("1.8"); + machineInfo.setOsName("linux"); + } + + @Test + public void testMachineInfo() { + machineInfo.setDeadLockThreadCount(3); + assertTrue(CollectionUtils.isNotEmpty(machineInfo.getDeadLockThreadInfoList())); + assertEquals(3, machineInfo.getDeadLockThreadCount()); + + } + + @Test + public void testDeadLockThreadInfo() { + assertEquals("name", deadLockThreadInfo.getName()); + assertEquals("lockName", deadLockThreadInfo.getLockName()); + assertEquals("lockOwner", deadLockThreadInfo.getLockOwner()); + assertEquals("state", deadLockThreadInfo.getState()); + assertEquals("stackTrace", deadLockThreadInfo.getStackTrace()); + assertEquals(0, deadLockThreadInfo.getBlockTime()); + assertEquals(0, deadLockThreadInfo.getWaitTime()); + + } + + @Test + public void testNodeInfo() { + NodeInfo nodeInfo = new NodeInfo(); + nodeInfo.setTotalFlow(1L); + nodeInfo.setCheatWitnessInfoMap(new HashMap<>()); + assertEquals(1, nodeInfo.getTotalFlow()); + assertNotNull(nodeInfo.getCheatWitnessInfoMap()); + nodeInfo.setMachineInfo(machineInfo); + nodeInfo.setBlock("block"); + nodeInfo.setSolidityBlock("solidityBlock"); + nodeInfo.transferToProtoEntity(); + } +} diff --git a/framework/src/test/java/org/tron/common/MultiLayoutPatternTest.java b/framework/src/test/java/org/tron/common/MultiLayoutPatternTest.java new file mode 100644 index 00000000000..87223757e8e --- /dev/null +++ b/framework/src/test/java/org/tron/common/MultiLayoutPatternTest.java @@ -0,0 +1,72 @@ +package org.tron.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggingEvent; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; +import org.tron.common.log.layout.MultiLayoutPattern; + +public class MultiLayoutPatternTest { + + private MultiLayoutPattern multiLayoutPattern; + private LoggerContext context; + + @Before + public void setUp() { + context = new LoggerContext(); + multiLayoutPattern = new MultiLayoutPattern(); + multiLayoutPattern.setContext(context); + + MultiLayoutPattern.Rule rule1 = new MultiLayoutPattern.Rule(); + rule1.setLogger("com.example.app1"); + assertNotNull(rule1.getLogger()); + rule1.setPattern("%date [%thread] %-5level %logger{36} - %msg%n"); + assertNotNull(rule1.getPattern()); + rule1.setOutputPatternAsHeader(true); + assertTrue(rule1.isOutputPatternAsHeader()); + multiLayoutPattern.addRule(rule1); + + MultiLayoutPattern.Rule rule2 = new MultiLayoutPattern.Rule(); + rule2.setLogger("com.example.app2"); + rule2.setPattern("%msg%n"); + multiLayoutPattern.addRule(rule2); + + multiLayoutPattern.start(); + } + + @Test + public void testEncodeForSpecificLogger() { + ILoggingEvent event1 = createLoggingEvent("com.example.app1", "Test message 1"); + byte[] encoded1 = multiLayoutPattern.encode(event1); + String result1 = new String(encoded1); + assertTrue(result1.contains("Test message 1")); + + ILoggingEvent event2 = createLoggingEvent("com.example.app2", "Test message 2"); + byte[] encoded2 = multiLayoutPattern.encode(event2); + String result2 = new String(encoded2); + assertEquals("Test message 2\n", result2); + } + + @Test + public void testEncodeForRootLogger() { + ILoggingEvent event = createLoggingEvent(Logger.ROOT_LOGGER_NAME, "Root logger message"); + byte[] encoded = multiLayoutPattern.encode(event); + String result = new String(encoded); + assertFalse(result.contains("Root logger message")); + } + + private ILoggingEvent createLoggingEvent(String loggerName, String message) { + Logger logger = (Logger) LoggerFactory.getLogger(loggerName); + return new LoggingEvent(loggerName, logger, Level.INFO, message, null, null); + } + +} diff --git a/framework/src/test/java/org/tron/common/ParameterTest.java b/framework/src/test/java/org/tron/common/ParameterTest.java new file mode 100644 index 00000000000..b16be405f61 --- /dev/null +++ b/framework/src/test/java/org/tron/common/ParameterTest.java @@ -0,0 +1,320 @@ +package org.tron.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.tron.common.parameter.RateLimiterInitialization.createHttpItem; +import static org.tron.common.parameter.RateLimiterInitialization.createRpcItem; +import static org.tron.core.Constant.ECKey_ENGINE; + +import com.google.common.collect.Lists; +import com.typesafe.config.ConfigFactory; +import com.typesafe.config.ConfigObject; +import java.util.ArrayList; +import java.util.HashSet; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.parameter.RateLimiterInitialization; +import org.tron.common.parameter.RateLimiterInitialization.HttpRateLimiterItem; +import org.tron.common.parameter.RateLimiterInitialization.RpcRateLimiterItem; +import org.tron.p2p.dns.update.PublishConfig; + +public class ParameterTest { + @Test + public void testConstructor_ValidConfig() { + String configStr = "{\"component\":\"testComponent\",\"strategy\":\"testStrategy\"," + + "\"paramString\":\"testParams\"}"; + ConfigObject config = ConfigFactory.parseString(configStr).root().toConfig().root(); + RpcRateLimiterItem item = new RpcRateLimiterItem(config); + HttpRateLimiterItem item1 = new HttpRateLimiterItem(config); + + assertEquals("testComponent", item.getComponent()); + assertEquals("testComponent", item1.getComponent()); + assertEquals("testStrategy", item.getStrategy()); + assertEquals("testParams", item.getParams()); + assertNull(createRpcItem(null)); + assertNull(createHttpItem(null)); + assertNotNull(createRpcItem(config)); + RateLimiterInitialization rateLimiterInitialization = new RateLimiterInitialization(); + rateLimiterInitialization.setRpcMap(Lists.newArrayList(item)); + assertFalse(rateLimiterInitialization.isHttpFlag()); + assertTrue(rateLimiterInitialization.isRpcFlag()); + } + + @Test + public void testCommonParameter() { + CommonParameter parameter = new CommonParameter(); + parameter.setWitness(false); + parameter.setSupportConstant(false); + parameter.setMaxEnergyLimitForConstant(1000000L); + parameter.setLruCacheSize(5); + parameter.setMinTimeRatio(0); + parameter.setMaxTimeRatio(20); + parameter.setSaveInternalTx(false); + parameter.setSaveFeaturedInternalTx(false); + parameter.setLongRunningTime(60); + parameter.setMaxHttpConnectNumber(5); + + assertEquals(StringUtils.EMPTY, parameter.getLogbackPath()); + assertEquals(1000000L, parameter.getMaxEnergyLimitForConstant()); + assertEquals(5, parameter.getLruCacheSize()); + assertEquals(60, parameter.getLongRunningTime()); + assertFalse(parameter.isHelp()); + assertFalse(parameter.isSaveFeaturedInternalTx()); + assertFalse(parameter.isSaveInternalTx()); + CollectionUtils.isEmpty(parameter.getSeedNodes()); + parameter.setChainId("123"); + assertEquals("123", parameter.getChainId()); + parameter.setNeedSyncCheck(false); + assertFalse(parameter.isNeedSyncCheck()); + parameter.setNodeDiscoveryEnable(false); + assertFalse(parameter.isNodeDiscoveryEnable()); + parameter.setNodeDiscoveryPersist(false); + assertFalse(parameter.isNodeDiscoveryPersist()); + parameter.setNodeEffectiveCheckEnable(false); + assertFalse(parameter.isNodeEffectiveCheckEnable()); + parameter.setNodeConnectionTimeout(500); + assertEquals(500, parameter.getNodeConnectionTimeout()); + parameter.setFetchBlockTimeout(500); + assertEquals(500, parameter.getFetchBlockTimeout()); + parameter.setNodeChannelReadTimeout(500); + assertEquals(500, parameter.getNodeChannelReadTimeout()); + parameter.setMaxConnections(500); + assertEquals(500, parameter.getMaxConnections()); + parameter.setMinConnections(500); + assertEquals(500, parameter.getMinConnections()); + parameter.setMinActiveConnections(500); + assertEquals(500, parameter.getMinActiveConnections()); + parameter.setMaxConnectionsWithSameIp(500); + assertEquals(500, parameter.getMaxConnectionsWithSameIp()); + parameter.setMaxTps(500); + assertEquals(500, parameter.getMaxTps()); + parameter.setMinParticipationRate(500); + assertEquals(500, parameter.getMinParticipationRate()); + parameter.setMaxConnectionsWithSameIp(500); + assertEquals(500, parameter.getMaxConnectionsWithSameIp()); + assertNull(parameter.getP2pConfig()); + parameter.setNodeLanIp("500"); + assertEquals("500", parameter.getNodeLanIp()); + parameter.setNodeP2pVersion(5); + assertEquals(5, parameter.getNodeP2pVersion()); + parameter.setNodeEnableIpv6(false); + assertFalse(parameter.isNodeEnableIpv6()); + parameter.setDnsTreeUrls(new ArrayList<>()); + assertTrue(CollectionUtils.isEmpty(parameter.getDnsTreeUrls())); + parameter.setDnsPublishConfig(new PublishConfig()); + parameter.setSyncFetchBatchNum(500); + assertEquals(500, parameter.getSyncFetchBatchNum()); + parameter.setDebug(false); + assertFalse(parameter.isDebug()); + parameter.setFullNodeHttpPort(80); + assertEquals(80, parameter.getFullNodeHttpPort()); + parameter.setSolidityHttpPort(80); + assertEquals(80, parameter.getSolidityHttpPort()); + parameter.setJsonRpcHttpFullNodePort(80); + assertEquals(80, parameter.getJsonRpcHttpFullNodePort()); + parameter.setJsonRpcHttpSolidityPort(80); + assertEquals(80, parameter.getJsonRpcHttpSolidityPort()); + parameter.setJsonRpcHttpPBFTPort(80); + assertEquals(80, parameter.getJsonRpcHttpPBFTPort()); + parameter.setRpcThreadNum(10); + assertEquals(10, parameter.getRpcThreadNum()); + parameter.setSolidityThreads(5); + assertEquals(5, parameter.getSolidityThreads()); + parameter.setMaxConcurrentCallsPerConnection(10); + assertEquals(10, parameter.getMaxConcurrentCallsPerConnection()); + parameter.setFlowControlWindow(20); + assertEquals(20, parameter.getFlowControlWindow()); + parameter.setMaxConnectionIdleInMillis(1000); + assertEquals(1000, parameter.getMaxConnectionIdleInMillis()); + parameter.setBlockProducedTimeOut(500); + assertEquals(500, parameter.getBlockProducedTimeOut()); + parameter.setNetMaxTrxPerSecond(15); + assertEquals(15, parameter.getNetMaxTrxPerSecond()); + parameter.setMaxConnectionAgeInMillis(1500); + assertEquals(1500, parameter.getMaxConnectionAgeInMillis()); + parameter.setMaxMessageSize(200); + assertEquals(200, parameter.getMaxMessageSize()); + parameter.setMaxHeaderListSize(100); + assertEquals(100, parameter.getMaxHeaderListSize()); + parameter.setRpcReflectionServiceEnable(false); + assertFalse(parameter.isRpcReflectionServiceEnable); + parameter.setValidateSignThreadNum(5); + assertEquals(5, parameter.getValidateSignThreadNum()); + parameter.setMaintenanceTimeInterval(200); + assertEquals(200, parameter.getMaintenanceTimeInterval()); + parameter.setProposalExpireTime(1000); + assertEquals(1000, parameter.getProposalExpireTime()); + parameter.setAllowCreationOfContracts(1); + assertEquals(1, parameter.getAllowCreationOfContracts()); + parameter.setAllowAdaptiveEnergy(1); + assertEquals(1, parameter.getAllowAdaptiveEnergy()); + parameter.setAllowDelegateResource(1); + assertEquals(1, parameter.getAllowDelegateResource()); + parameter.setAllowSameTokenName(1); + assertEquals(1, parameter.getAllowSameTokenName()); + parameter.setAllowTvmTransferTrc10(1); + assertEquals(1, parameter.getAllowTvmTransferTrc10()); + parameter.setAllowTvmConstantinople(1); + assertEquals(1, parameter.getAllowTvmConstantinople()); + parameter.setAllowTvmSolidity059(1); + assertEquals(1, parameter.getAllowTvmSolidity059()); + parameter.setForbidTransferToContract(1); + assertEquals(1, parameter.getForbidTransferToContract()); + parameter.setTcpNettyWorkThreadNum(5); + assertEquals(5, parameter.getTcpNettyWorkThreadNum()); + parameter.setUdpNettyWorkThreadNum(5); + assertEquals(5, parameter.getUdpNettyWorkThreadNum()); + parameter.setTrustNodeAddr("address"); + assertEquals("address", parameter.getTrustNodeAddr()); + parameter.setWalletExtensionApi(false); + assertFalse(parameter.isWalletExtensionApi()); + parameter.setEstimateEnergy(false); + assertFalse(parameter.isEstimateEnergy()); + parameter.setEstimateEnergyMaxRetry(2); + assertEquals(2, parameter.getEstimateEnergyMaxRetry()); + parameter.setKeepAliveInterval(1000); + assertEquals(1000, parameter.getKeepAliveInterval()); + parameter.setReceiveTcpMinDataLength(10); + assertEquals(10, parameter.getReceiveTcpMinDataLength()); + parameter.setOpenFullTcpDisconnect(false); + assertFalse(parameter.isOpenFullTcpDisconnect()); + parameter.setNodeDetectEnable(false); + assertFalse(parameter.isNodeDetectEnable()); + parameter.setAllowMultiSign(1); + assertEquals(1, parameter.getAllowMultiSign()); + parameter.setVmTrace(false); + assertFalse(parameter.isVmTrace()); + parameter.setNeedToUpdateAsset(false); + assertFalse(parameter.isNeedToUpdateAsset()); + parameter.setTrxReferenceBlock("test"); + assertEquals("test", parameter.getTrxReferenceBlock()); + parameter.setTrxCacheEnable(false); + assertFalse(parameter.isTrxCacheEnable()); + parameter.setAllowMarketTransaction(1); + assertEquals(1, parameter.getAllowMarketTransaction()); + parameter.setAllowTransactionFeePool(1); + assertEquals(1, parameter.getAllowTransactionFeePool()); + parameter.setAllowBlackHoleOptimization(1); + assertEquals(1, parameter.getAllowBlackHoleOptimization()); + parameter.setAllowNewResourceModel(1); + assertEquals(1, parameter.getAllowNewResourceModel()); + parameter.setEventSubscribe(false); + assertFalse(parameter.isEventSubscribe()); + parameter.setTrxExpirationTimeInMilliseconds(100); + assertEquals(100, parameter.getTrxExpirationTimeInMilliseconds()); + parameter.setAllowProtoFilterNum(10); + assertEquals(10, parameter.getAllowProtoFilterNum()); + parameter.setShieldedTransInPendingMaxCounts(1); + assertEquals(1, parameter.getShieldedTransInPendingMaxCounts()); + parameter.setChangedDelegation(1); + assertEquals(1, parameter.getChangedDelegation()); + parameter.setActuatorSet(new HashSet<>()); + assertTrue(CollectionUtils.isEmpty(parameter.getActuatorSet())); + parameter.setRateLimiterInitialization(new RateLimiterInitialization()); + assertNotNull(parameter.getRateLimiterInitialization()); + parameter.setRateLimiterGlobalQps(1000); + assertEquals(1000, parameter.getRateLimiterGlobalQps()); + parameter.setRateLimiterGlobalIpQps(100); + assertEquals(100, parameter.getRateLimiterGlobalIpQps()); + assertNull(parameter.getOverlay()); + assertNull(parameter.getEventPluginConfig()); + assertNull(parameter.getEventFilter()); + parameter.setCryptoEngine(ECKey_ENGINE); + assertEquals(ECKey_ENGINE, parameter.getCryptoEngine()); + parameter.setFullNodeHttpEnable(false); + assertFalse(parameter.isFullNodeHttpEnable()); + parameter.setSolidityNodeHttpEnable(false); + assertFalse(parameter.isSolidityNodeHttpEnable()); + parameter.setMaxTransactionPendingSize(500); + assertEquals(500, parameter.getMaxTransactionPendingSize()); + parameter.setPendingTransactionTimeout(500); + assertEquals(500, parameter.getPendingTransactionTimeout()); + parameter.setNodeMetricsEnable(false); + assertFalse(parameter.isNodeMetricsEnable()); + parameter.setMetricsStorageEnable(false); + assertFalse(parameter.isMetricsStorageEnable()); + parameter.setInfluxDbIp("127.0.0.1"); + assertEquals("127.0.0.1", parameter.getInfluxDbIp()); + parameter.setInfluxDbPort(90); + assertEquals(90, parameter.getInfluxDbPort()); + parameter.setInfluxDbDatabase("InfluxDb"); + assertEquals("InfluxDb", parameter.getInfluxDbDatabase()); + parameter.setMetricsReportInterval(100); + assertEquals(100, parameter.getMetricsReportInterval()); + parameter.setMetricsPrometheusPort(3000); + assertEquals(3000, parameter.getMetricsPrometheusPort()); + parameter.setAgreeNodeCount(10); + assertEquals(10, parameter.getAgreeNodeCount()); + parameter.setAllowPBFT(1); + assertEquals(1, parameter.getAllowPBFT()); + parameter.setPBFTHttpPort(70); + assertEquals(70, parameter.getPBFTHttpPort()); + parameter.setPBFTExpireNum(100); + assertEquals(100, parameter.getPBFTExpireNum()); + parameter.setAllowShieldedTRC20Transaction(10); + assertEquals(10, parameter.getAllowShieldedTRC20Transaction()); + parameter.setAllowTvmIstanbul(1); + assertEquals(1, parameter.getAllowTvmIstanbul()); + parameter.setAllowTvmVote(1); + assertEquals(1, parameter.getAllowTvmVote()); + parameter.setAllowTvmLondon(1); + assertEquals(1, parameter.getAllowTvmLondon()); + parameter.setAllowTvmCompatibleEvm(1); + assertEquals(1, parameter.getAllowTvmCompatibleEvm()); + parameter.setAllowHigherLimitForMaxCpuTimeOfOneTx(1); + assertEquals(1, parameter.getAllowHigherLimitForMaxCpuTimeOfOneTx()); + parameter.setHistoryBalanceLookup(false); + assertFalse(parameter.isHistoryBalanceLookup()); + parameter.setOpenPrintLog(false); + assertFalse(parameter.isOpenPrintLog()); + parameter.setOpenTransactionSort(false); + assertFalse(parameter.isOpenTransactionSort()); + parameter.setAllowAssetOptimization(1); + assertEquals(1, parameter.getAllowAssetOptimization()); + parameter.setAllowAccountAssetOptimization(1); + assertEquals(1, parameter.getAllowAccountAssetOptimization()); + parameter.setBlockCacheTimeout(60); + assertEquals(60, parameter.getBlockCacheTimeout()); + parameter.setAllowNewReward(1); + assertEquals(1, parameter.getAllowNewReward()); + parameter.setAllowNewRewardAlgorithm(1); + assertEquals(1, parameter.getAllowNewRewardAlgorithm()); + parameter.setMemoFee(100); + assertEquals(100, parameter.getMemoFee()); + parameter.setAllowDelegateOptimization(1); + assertEquals(1, parameter.getAllowDelegateOptimization()); + parameter.setUnfreezeDelayDays(10); + assertEquals(10, parameter.getUnfreezeDelayDays()); + parameter.setAllowOptimizedReturnValueOfChainId(1); + assertEquals(1, parameter.getAllowOptimizedReturnValueOfChainId()); + parameter.setAllowDynamicEnergy(1); + assertEquals(1, parameter.getAllowDynamicEnergy()); + parameter.setDynamicEnergyThreshold(1); + assertEquals(1, parameter.getDynamicEnergyThreshold()); + parameter.setDynamicEnergyIncreaseFactor(1); + assertEquals(1, parameter.getDynamicEnergyIncreaseFactor()); + parameter.setDynamicEnergyMaxFactor(1); + assertEquals(1, parameter.getDynamicEnergyMaxFactor()); + parameter.setDynamicConfigEnable(false); + assertFalse(parameter.isDynamicConfigEnable()); + parameter.setDynamicConfigCheckInterval(10); + assertEquals(10, parameter.getDynamicConfigCheckInterval()); + parameter.setAllowTvmShangHai(1); + assertEquals(1, parameter.getAllowTvmShangHai()); + parameter.setAllowCancelAllUnfreezeV2(1); + assertEquals(1, parameter.getAllowCancelAllUnfreezeV2()); + parameter.setMaxUnsolidifiedBlocks(100); + assertEquals(100, parameter.getMaxUnsolidifiedBlocks()); + parameter.setAllowOldRewardOpt(1); + assertEquals(1, parameter.getAllowOldRewardOpt()); + parameter.setAllowEnergyAdjustment(1); + assertEquals(1, parameter.getAllowEnergyAdjustment()); + parameter.setMaxCreateAccountTxSize(1000); + assertEquals(1000, parameter.getMaxCreateAccountTxSize()); + } +} diff --git a/framework/src/test/java/org/tron/common/cache/TronCacheTest.java b/framework/src/test/java/org/tron/common/cache/TronCacheTest.java new file mode 100644 index 00000000000..422bd1de881 --- /dev/null +++ b/framework/src/test/java/org/tron/common/cache/TronCacheTest.java @@ -0,0 +1,100 @@ +package org.tron.common.cache; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.tron.common.cache.CacheManager.allocate; +import static org.tron.common.cache.CacheStrategies.CACHE_STRATEGY_DEFAULT; +import static org.tron.common.cache.CacheType.findByType; +import static org.tron.common.cache.CacheType.witness; +import static org.tron.common.cache.CacheType.witnessStandby; + +import com.google.common.cache.CacheLoader; +import java.util.concurrent.ExecutionException; +import javax.annotation.ParametersAreNonnullByDefault; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; + +@Slf4j +public class TronCacheTest { + + private TronCache cacheWithLoader; + private TronCache cacheWithoutLoader; + CacheLoader loader = new CacheLoader() { + @Override + @ParametersAreNonnullByDefault + public String load(String key) { + return "Loaded: " + key; + } + }; + + @Before + public void setUp() { + + cacheWithLoader = new TronCache<>(witness, CACHE_STRATEGY_DEFAULT, loader); + + cacheWithoutLoader = new TronCache<>(witnessStandby, CACHE_STRATEGY_DEFAULT); + } + + @Test + public void testGetIfPresent() { + cacheWithoutLoader.put("key1", "value1"); + assertEquals("value1", cacheWithoutLoader.getIfPresent("key1")); + assertNull(cacheWithoutLoader.getIfPresent("key2")); + } + + @Test + public void testGetWithLoader() throws ExecutionException { + String value = cacheWithLoader.get("key1", () -> "Fallback value"); + assertEquals("Fallback value", value); + } + + @Test + public void testPutAndGet() { + cacheWithoutLoader.put("key2", "value2"); + assertEquals("value2", cacheWithoutLoader.getIfPresent("key2")); + assertEquals(witnessStandby, cacheWithoutLoader.getName()); + logger.info("hash code: {}", cacheWithoutLoader.hashCode()); + } + + @Test + public void testStats() { + cacheWithoutLoader.put("key3", "value3"); + assertNotNull(cacheWithoutLoader.stats()); + assertEquals(0, cacheWithoutLoader.stats().hitCount()); + cacheWithoutLoader.getIfPresent("key3"); + assertTrue(cacheWithoutLoader.stats().hitCount() > 0); + } + + @Test + public void testInvalidateAll() { + cacheWithoutLoader.put("key4", "value4"); + assertEquals("value4", cacheWithoutLoader.getIfPresent("key4")); + cacheWithoutLoader.invalidateAll(); + assertNull(cacheWithoutLoader.getIfPresent("key4")); + } + + @Test + public void testEquals() { + TronCache tmpCache = cacheWithoutLoader; + assertEquals(cacheWithoutLoader, tmpCache); + assertNotEquals(cacheWithoutLoader, new Object()); + assertNotEquals(cacheWithoutLoader, cacheWithLoader); + tmpCache = new TronCache<>(witnessStandby, CACHE_STRATEGY_DEFAULT); + assertEquals(cacheWithoutLoader, tmpCache); + } + + @Test + public void testCacheManager() { + TronCache allocate = allocate(witness, CACHE_STRATEGY_DEFAULT); + TronCache allocate1 = allocate(witness, CACHE_STRATEGY_DEFAULT, loader); + assertNotNull(allocate); + assertNotNull(allocate1); + assertThrows(IllegalArgumentException.class, () -> findByType("test")); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java index 8ff8167f52e..1e5268ddeb6 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java @@ -1,5 +1,9 @@ package org.tron.common.logsfilter; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import java.util.ArrayList; import java.util.List; import org.junit.Assert; @@ -15,18 +19,31 @@ public void launchNativeQueue() { config.setSendQueueLength(1000); config.setBindPort(5555); config.setUseNativeQueue(true); + config.setPluginPath("pluginPath"); + config.setServerAddress("serverAddress"); + config.setDbConfig("dbConfig"); + assertEquals("pluginPath", config.getPluginPath()); + assertEquals("serverAddress", config.getServerAddress()); + assertEquals("dbConfig", config.getDbConfig()); List triggerConfigList = new ArrayList<>(); - TriggerConfig blockTriggerConfig = new TriggerConfig(); - blockTriggerConfig.setTriggerName("block"); - blockTriggerConfig.setEnabled(true); - blockTriggerConfig.setTopic("block"); - triggerConfigList.add(blockTriggerConfig); + TriggerConfig triggerConfig = new TriggerConfig(); + triggerConfig.setTriggerName("block"); + triggerConfig.setEnabled(true); + triggerConfig.setTopic("topic"); + triggerConfig.setRedundancy(false); + triggerConfig.setEthCompatible(false); + triggerConfig.setSolidified(false); + assertFalse(triggerConfig.isRedundancy()); + assertFalse(triggerConfig.isEthCompatible()); + assertFalse(triggerConfig.isSolidified()); + assertEquals("topic", triggerConfig.getTopic()); + triggerConfigList.add(triggerConfig); config.setTriggerConfigList(triggerConfigList); - Assert.assertTrue(EventPluginLoader.getInstance().start(config)); + assertTrue(EventPluginLoader.getInstance().start(config)); EventPluginLoader.getInstance().stopPlugin(); } diff --git a/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java b/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java index 601cf72b294..5ee32d98ee6 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java @@ -1,6 +1,13 @@ package org.tron.common.logsfilter; +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.tron.common.logsfilter.EventPluginLoader.matchFilter; +import static org.tron.common.logsfilter.FilterQuery.EARLIEST_BLOCK_NUM; +import static org.tron.common.logsfilter.FilterQuery.LATEST_BLOCK_NUM; import static org.tron.common.logsfilter.FilterQuery.parseFromBlockNumber; import static org.tron.common.logsfilter.FilterQuery.parseToBlockNumber; @@ -9,54 +16,57 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.tron.common.logsfilter.capsule.ContractEventTriggerCapsule; +import org.tron.common.logsfilter.capsule.FilterTriggerCapsule; +import org.tron.common.logsfilter.capsule.TriggerCapsule; import org.tron.common.runtime.LogEventWrapper; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI.Entry; +@Slf4j public class FilterQueryTest { @Test public synchronized void testParseFilterQueryBlockNumber() { - { - String blockNum = ""; - Assert.assertEquals(FilterQuery.LATEST_BLOCK_NUM, parseToBlockNumber(blockNum)); - } + assertEquals(LATEST_BLOCK_NUM, parseToBlockNumber(EMPTY)); + assertEquals(13245, parseToBlockNumber("13245")); - { - String blockNum = "earliest"; - Assert.assertEquals(FilterQuery.EARLIEST_BLOCK_NUM, parseFromBlockNumber(blockNum)); - } + assertEquals(EARLIEST_BLOCK_NUM, parseFromBlockNumber("earliest")); + assertEquals(13245, parseFromBlockNumber("13245")); + assertThrows(Exception.class, () -> parseFromBlockNumber("test")); + assertThrows(Exception.class, () -> parseToBlockNumber("test")); - { - String blockNum = "13245"; - Assert.assertEquals(13245, parseToBlockNumber(blockNum)); - } } @Test public synchronized void testMatchFilter() { - String[] addrList = {"address1", "address2"}; + String[] adrList = {"address1", "address2"}; String[] topList = {"top1", "top2"}; - Map topMap = new HashMap(); + Map topMap = new HashMap<>(); List addressList = new ArrayList<>(); - addressList.add(addrList[0].getBytes()); - addressList.add(addrList[1].getBytes()); + addressList.add(adrList[0].getBytes()); + addressList.add(adrList[1].getBytes()); topMap.put("1", topList[0]); topMap.put("2", topList[1]); LogEventWrapper event = new LogEventWrapper(); - ((LogEventWrapper) event).setTopicList(addressList); - ((LogEventWrapper) event).setData(new byte[]{}); - ((LogEventWrapper) event).setEventSignature(""); - ((LogEventWrapper) event).setAbiEntry(Entry.newBuilder().setName("testABI").build()); - event.setBlockNumber(new Long(123)); + event.setTopicList(addressList); + event.setData(new byte[]{}); + event.setEventSignature(""); + event.setAbiEntry(Entry.newBuilder().setName("testABI").build()); + event.setBlockNumber(123L); ContractEventTriggerCapsule capsule = new ContractEventTriggerCapsule(event); + capsule.setContractEventTrigger(capsule.getContractEventTrigger()); capsule.getContractEventTrigger().setContractAddress("address1"); + capsule.setLatestSolidifiedBlockNumber(0L); + capsule.setData(capsule.getData()); + capsule.setTopicList(capsule.getTopicList()); + capsule.setAbiEntry(capsule.getAbiEntry()); capsule.getContractEventTrigger().setTopicMap(topMap); { - Assert.assertEquals(true, matchFilter(capsule.getContractEventTrigger())); + Assert.assertTrue(matchFilter(capsule.getContractEventTrigger())); } { @@ -64,7 +74,7 @@ public synchronized void testMatchFilter() { filterQuery.setFromBlock(1); filterQuery.setToBlock(100); EventPluginLoader.getInstance().setFilterQuery(filterQuery); - Assert.assertEquals(false, matchFilter(capsule.getContractEventTrigger())); + Assert.assertFalse(matchFilter(capsule.getContractEventTrigger())); } { @@ -72,17 +82,33 @@ public synchronized void testMatchFilter() { filterQuery.setFromBlock(133); filterQuery.setToBlock(190); EventPluginLoader.getInstance().setFilterQuery(filterQuery); - Assert.assertEquals(false, matchFilter(capsule.getContractEventTrigger())); + Assert.assertFalse(matchFilter(capsule.getContractEventTrigger())); } { FilterQuery filterQuery = new FilterQuery(); filterQuery.setFromBlock(100); filterQuery.setToBlock(190); - filterQuery.setContractAddressList(Arrays.asList(addrList)); + filterQuery.setContractAddressList(Arrays.asList(adrList)); filterQuery.setContractTopicList(Arrays.asList(topList)); EventPluginLoader.getInstance().setFilterQuery(filterQuery); - Assert.assertEquals(true, matchFilter(capsule.getContractEventTrigger())); + Assert.assertTrue(matchFilter(capsule.getContractEventTrigger())); + capsule.processTrigger(); + assertNotNull(filterQuery.toString()); + } + + FilterTriggerCapsule filterTriggerCapsule = new FilterTriggerCapsule(); + try { + filterTriggerCapsule.processFilterTrigger(); + } catch (Exception e) { + logger.info(e.getMessage()); + } + + TriggerCapsule triggerCapsule = new TriggerCapsule(); + try { + triggerCapsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof UnsupportedOperationException); } } } 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 new file mode 100644 index 00000000000..5381c6ab2de --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java @@ -0,0 +1,38 @@ +package org.tron.common.logsfilter.capsule; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; + +public class BlockFilterCapsuleTest { + + private BlockFilterCapsule blockFilterCapsule; + + @Before + public void setUp() { + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + blockFilterCapsule = new BlockFilterCapsule(blockCapsule, false); + } + + @Test + public void testSetAndGetBlockHash() { + blockFilterCapsule + .setBlockHash("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f"); + System.out.println(blockFilterCapsule); + Assert.assertEquals("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", + blockFilterCapsule.getBlockHash()); + } + + @Test + public void testSetAndIsSolidified() { + blockFilterCapsule = new BlockFilterCapsule( + "e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", false); + blockFilterCapsule.setSolidified(true); + blockFilterCapsule.processFilterTrigger(); + Assert.assertTrue(blockFilterCapsule.isSolidified()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockLogTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockLogTriggerCapsuleTest.java new file mode 100644 index 00000000000..f77869b8650 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockLogTriggerCapsuleTest.java @@ -0,0 +1,35 @@ +package org.tron.common.logsfilter.capsule; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; + +public class BlockLogTriggerCapsuleTest { + + private BlockLogTriggerCapsule blockLogTriggerCapsule; + + @Before + public void setUp() { + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + blockLogTriggerCapsule = new BlockLogTriggerCapsule(blockCapsule); + } + + @Test + public void testSetAndGetBlockLogTrigger() { + blockLogTriggerCapsule + .setBlockLogTrigger(blockLogTriggerCapsule.getBlockLogTrigger()); + Assert.assertEquals(1, + blockLogTriggerCapsule.getBlockLogTrigger().getBlockNumber()); + } + + @Test + public void testSetLatestSolidifiedBlockNumber() { + blockLogTriggerCapsule.setLatestSolidifiedBlockNumber(100); + Assert.assertEquals(100, + blockLogTriggerCapsule.getBlockLogTrigger().getLatestSolidifiedBlockNumber()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractLogTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractLogTriggerCapsuleTest.java new file mode 100644 index 00000000000..3d45eb026ea --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractLogTriggerCapsuleTest.java @@ -0,0 +1,36 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.tron.common.logsfilter.trigger.Trigger.CONTRACTLOG_TRIGGER_NAME; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractLogTrigger; + +@Slf4j +public class ContractLogTriggerCapsuleTest { + + private ContractLogTriggerCapsule capsule; + + @Before + public void setUp() { + ContractLogTrigger contractLogTrigger = new ContractLogTrigger(); + contractLogTrigger.setBlockNumber(0L); + capsule = new ContractLogTriggerCapsule(contractLogTrigger); + capsule.setLatestSolidifiedBlockNumber(0); + } + + @Test + public void testSetAndGetContractLogTrigger() { + capsule.setContractLogTrigger(capsule.getContractLogTrigger()); + assertEquals(CONTRACTLOG_TRIGGER_NAME, capsule.getContractLogTrigger().getTriggerName()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsuleTest.java new file mode 100644 index 00000000000..898447b3a75 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsuleTest.java @@ -0,0 +1,70 @@ +package org.tron.common.logsfilter.capsule; + +import static com.google.common.collect.Lists.newArrayList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.beust.jcommander.internal.Lists; +import java.util.ArrayList; +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractTrigger; +import org.tron.common.runtime.vm.DataWord; +import org.tron.common.runtime.vm.LogInfo; + +@Slf4j +public class ContractTriggerCapsuleTest { + + private ContractTriggerCapsule capsule; + + private LogInfo logInfo; + + @Before + public void setUp() { + ContractTrigger contractTrigger = new ContractTrigger(); + contractTrigger.setBlockNumber(0L); + contractTrigger.setRemoved(false); + logInfo = new LogInfo(bytesToAddress(new byte[] {0x11}), + newArrayList(new DataWord()), new byte[0]); + contractTrigger.setLogInfo(logInfo); + contractTrigger.setRawData(new RawData(null, null, null)); + contractTrigger.setAbi(contractTrigger.getAbi()); + capsule = new ContractTriggerCapsule(contractTrigger); + + } + + private byte[] bytesToAddress(byte[] address) { + byte[] data = new byte[20]; + System.arraycopy(address, 0, data, 20 - address.length, address.length); + return data; + } + + @Test + public void testSetAndGetContractTrigger() { + capsule.setContractTrigger(capsule.getContractTrigger()); + capsule.setBlockHash("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f"); + capsule.setLatestSolidifiedBlockNumber(0); + assertEquals(0, capsule.getContractTrigger().getLatestSolidifiedBlockNumber()); + assertEquals("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", + capsule.getContractTrigger().getBlockHash()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + + @Test + public void testLogInfo() { + logger.info("log info to string: {}, ", logInfo.toString()); + logger.info("log clone data: {}, ", logInfo.getClonedData()); + CollectionUtils.isNotEmpty(logInfo.getClonedTopics()); + CollectionUtils.isNotEmpty(logInfo.getHexTopics()); + new LogInfo(null, null, null); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/LogsFilterCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/LogsFilterCapsuleTest.java new file mode 100644 index 00000000000..691a3106b49 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/LogsFilterCapsuleTest.java @@ -0,0 +1,33 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.bloom.Bloom; + +public class LogsFilterCapsuleTest { + + private LogsFilterCapsule capsule; + + @Before + public void setUp() { + capsule = new LogsFilterCapsule(0, + "e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", + new Bloom(), new ArrayList<>(), true, false); + } + + @Test + public void testSetAndGetLogsFilterCapsule() { + capsule.setBlockNumber(capsule.getBlockNumber()); + capsule.setBlockHash(capsule.getBlockHash()); + capsule.setSolidified(capsule.isSolidified()); + capsule.setBloom(capsule.getBloom()); + capsule.setRemoved(capsule.isRemoved()); + capsule.setTxInfoList(capsule.getTxInfoList()); + assertNotNull(capsule.toString()); + capsule.processFilterTrigger(); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/RawDataTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/RawDataTest.java new file mode 100644 index 00000000000..c14afcd903b --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/RawDataTest.java @@ -0,0 +1,33 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import org.tron.common.runtime.vm.DataWord; + +public class RawDataTest { + @Test + public void testRawDataConstructor() { + byte[] addressBytes = {0x01, 0x02, 0x03, 0x04}; + byte[] dataBytes = {0x10, 0x20, 0x30, 0x40}; + List topics = Arrays.asList( + new DataWord("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), + new DataWord("0000000000000000000000000000000000000000000000000000000000000001")); + + RawData rawData = new RawData(addressBytes, topics, dataBytes); + + assertEquals("01020304", rawData.getAddress()); + assertEquals(topics, rawData.getTopics()); + assertEquals("10203040", rawData.getData()); + + rawData = new RawData(null, null, null); + assertEquals("", rawData.getAddress()); + assertTrue(rawData.getTopics().isEmpty()); + assertEquals("", rawData.getData()); + assertNotNull(rawData.toString()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityEventCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityEventCapsuleTest.java new file mode 100644 index 00000000000..9259ca3ea97 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityEventCapsuleTest.java @@ -0,0 +1,32 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertTrue; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractEventTrigger; + +@Slf4j +public class SolidityEventCapsuleTest { + + private SolidityEventCapsule capsule; + + @Before + public void setUp() { + ContractEventTrigger contractEventTrigger = new ContractEventTrigger(); + capsule = new SolidityEventCapsule(contractEventTrigger); + } + + @Test + public void testSetAndGetSolidityEventCapsule() { + capsule.setSolidityEventTrigger(capsule.getSolidityEventTrigger()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityLogCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityLogCapsuleTest.java new file mode 100644 index 00000000000..4e663930530 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityLogCapsuleTest.java @@ -0,0 +1,31 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertTrue; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractLogTrigger; + +@Slf4j +public class SolidityLogCapsuleTest { + + private SolidityLogCapsule capsule; + + @Before + public void setUp() { + ContractLogTrigger trigger = new ContractLogTrigger(); + capsule = new SolidityLogCapsule(trigger); + } + + @Test + public void testSetAndGetSolidityLogCapsule() { + capsule.setSolidityLogTrigger(capsule.getSolidityLogTrigger()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityTriggerCapsuleTest.java new file mode 100644 index 00000000000..849803c1f04 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityTriggerCapsuleTest.java @@ -0,0 +1,37 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.SolidityTrigger; + +@Slf4j +public class SolidityTriggerCapsuleTest { + + private SolidityTriggerCapsule capsule; + + @Before + public void setUp() { + capsule = new SolidityTriggerCapsule(0); + SolidityTrigger trigger = new SolidityTrigger(); + assertNotNull(trigger.toString()); + capsule.setSolidityTrigger(trigger); + capsule.setTimeStamp(System.currentTimeMillis()); + } + + @Test + public void testSetAndGetSolidityLogCapsule() { + capsule.setSolidityTrigger(capsule.getSolidityTrigger()); + capsule.setTimeStamp(capsule.getSolidityTrigger().getTimeStamp()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/trigger/ContractLogTriggerTest.java b/framework/src/test/java/org/tron/common/logsfilter/trigger/ContractLogTriggerTest.java new file mode 100644 index 00000000000..8d6e044c134 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/trigger/ContractLogTriggerTest.java @@ -0,0 +1,82 @@ +package org.tron.common.logsfilter.trigger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.Arrays; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.capsule.RawData; +import org.tron.common.runtime.vm.DataWord; + +public class ContractLogTriggerTest { + private ContractEventTrigger mockEventTrigger; + + @Before + public void setUp() { + mockEventTrigger = new ContractEventTrigger(); + byte[] addressBytes = {0x01, 0x02, 0x03, 0x04}; + byte[] dataBytes = {0x10, 0x20, 0x30, 0x40}; + List topics = Arrays.asList( + new DataWord("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), + new DataWord("0000000000000000000000000000000000000000000000000000000000000001")); + + RawData rawData = new RawData(addressBytes, topics, dataBytes); + mockEventTrigger.setRawData(rawData); + mockEventTrigger.setLatestSolidifiedBlockNumber(12345L); + mockEventTrigger.setRemoved(false); + mockEventTrigger.setUniqueId("unique-id"); + mockEventTrigger.setTransactionId("tx-id"); + mockEventTrigger.setContractAddress("contract-addr"); + mockEventTrigger.setOriginAddress("origin-addr"); + mockEventTrigger.setCreatorAddress("creator-addr"); + mockEventTrigger.setBlockNumber(67890L); + mockEventTrigger.setTimeStamp(1622547200L); + mockEventTrigger.setBlockHash("block-hash"); + } + + @Test + public void testDefaultConstructor() { + ContractLogTrigger trigger = new ContractLogTrigger(); + assertEquals(Trigger.CONTRACTLOG_TRIGGER_NAME, trigger.getTriggerName()); + assertNull(trigger.getTopicList()); + assertNull(trigger.getData()); + } + + @Test + public void testConstructorWithEventTrigger() { + ContractLogTrigger trigger = new ContractLogTrigger(mockEventTrigger); + assertEquals(Trigger.CONTRACTLOG_TRIGGER_NAME, trigger.getTriggerName()); + assertEquals(mockEventTrigger.getRawData(), trigger.getRawData()); + assertEquals(mockEventTrigger.getLatestSolidifiedBlockNumber(), + trigger.getLatestSolidifiedBlockNumber()); + assertEquals(mockEventTrigger.isRemoved(), trigger.isRemoved()); + assertEquals(mockEventTrigger.getUniqueId(), trigger.getUniqueId()); + assertEquals(mockEventTrigger.getTransactionId(), trigger.getTransactionId()); + assertEquals(mockEventTrigger.getContractAddress(), trigger.getContractAddress()); + assertEquals(mockEventTrigger.getOriginAddress(), trigger.getOriginAddress()); + assertEquals("", trigger.getCallerAddress()); // Explicitly set to empty string + assertEquals(mockEventTrigger.getCreatorAddress(), trigger.getCreatorAddress()); + assertEquals(mockEventTrigger.getBlockNumber(), trigger.getBlockNumber()); + assertEquals(mockEventTrigger.getTimeStamp(), trigger.getTimeStamp()); + assertEquals(mockEventTrigger.getBlockHash(), trigger.getBlockHash()); + } + + @Test + public void testSetAndGetTopicList() { + ContractLogTrigger trigger = new ContractLogTrigger(); + List topics = Arrays.asList("topic1", "topic2"); + trigger.setTopicList(topics); + assertEquals(topics, trigger.getTopicList()); + } + + @Test + public void testSetAndGetData() { + ContractLogTrigger trigger = new ContractLogTrigger(); + String testData = "log data"; + trigger.setData(testData); + assertEquals(testData, trigger.getData()); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/trigger/InternalTransactionPojoTest.java b/framework/src/test/java/org/tron/common/logsfilter/trigger/InternalTransactionPojoTest.java new file mode 100644 index 00000000000..9948c5535af --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/trigger/InternalTransactionPojoTest.java @@ -0,0 +1,87 @@ +package org.tron.common.logsfilter.trigger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class InternalTransactionPojoTest { + private InternalTransactionPojo internalTransactionPojo; + + @Before + public void setUp() { + internalTransactionPojo = new InternalTransactionPojo(); + } + + @Test + public void testHash() { + String testHash = "0x123456789abcdef0123456789abcdef0"; + internalTransactionPojo.setHash(testHash); + assertEquals(testHash, internalTransactionPojo.getHash()); + } + + @Test + public void testCallValue() { + long testCallValue = 123456789L; + internalTransactionPojo.setCallValue(testCallValue); + assertEquals(testCallValue, internalTransactionPojo.getCallValue()); + } + + @Test + public void testTokenInfo() { + Map testTokenInfo = new HashMap<>(); + testTokenInfo.put("token1", 100L); + testTokenInfo.put("token2", 200L); + internalTransactionPojo.setTokenInfo(testTokenInfo); + assertEquals(testTokenInfo, internalTransactionPojo.getTokenInfo()); + } + + @Test + public void testTransferToAddress() { + String testAddress = "0x0000000000000000000000000000000000000001"; + internalTransactionPojo.setTransferTo_address(testAddress); + assertEquals(testAddress, internalTransactionPojo.getTransferTo_address()); + } + + @Test + public void testData() { + String testData = "0x6060604052341561000f57600080fd5b5b6040516020806101158339810160405280805" + + "19060200190929190505050"; + internalTransactionPojo.setData(testData); + assertEquals(testData, internalTransactionPojo.getData()); + } + + @Test + public void testCallerAddress() { + String testCallerAddress = "0x0000000000000000000000000000000000000002"; + internalTransactionPojo.setCaller_address(testCallerAddress); + assertEquals(testCallerAddress, internalTransactionPojo.getCaller_address()); + } + + @Test + public void testRejected() { + internalTransactionPojo.setRejected(true); + assertTrue(internalTransactionPojo.isRejected()); + + internalTransactionPojo.setRejected(false); + assertFalse(internalTransactionPojo.isRejected()); + } + + @Test + public void testNote() { + String testNote = "This is a test note"; + internalTransactionPojo.setNote(testNote); + assertEquals(testNote, internalTransactionPojo.getNote()); + } + + @Test + public void testExtra() { + String testExtra = "extra_data_for_vote_witness"; + internalTransactionPojo.setExtra(testExtra); + assertEquals(testExtra, internalTransactionPojo.getExtra()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/trigger/LogPojoTest.java b/framework/src/test/java/org/tron/common/logsfilter/trigger/LogPojoTest.java new file mode 100644 index 00000000000..7c94ec4f7ad --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/trigger/LogPojoTest.java @@ -0,0 +1,74 @@ +package org.tron.common.logsfilter.trigger; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import org.junit.Before; +import org.junit.Test; + +public class LogPojoTest { + + private LogPojo logPojo; + + @Before + public void setUp() { + logPojo = new LogPojo(); + } + + @Test + public void testAddress() { + String testAddress = "123 Test Address"; + logPojo.setAddress(testAddress); + assertEquals(testAddress, logPojo.getAddress()); + } + + @Test + public void testBlockHash() { + String testBlockHash = "abcdef1234567890abcdef1234567890abcdef12"; + logPojo.setBlockHash(testBlockHash); + assertEquals(testBlockHash, logPojo.getBlockHash()); + } + + @Test + public void testBlockNumber() { + long testBlockNumber = 1234567L; + logPojo.setBlockNumber(testBlockNumber); + assertEquals(testBlockNumber, logPojo.getBlockNumber()); + } + + @Test + public void testData() { + String testData = "Some data here"; + logPojo.setData(testData); + assertEquals(testData, logPojo.getData()); + } + + @Test + public void testLogIndex() { + long testLogIndex = 5L; + logPojo.setLogIndex(testLogIndex); + assertEquals(testLogIndex, logPojo.getLogIndex()); + } + + @Test + public void testTopicList() { + List testTopicList = Arrays.asList("topic1", "topic2", "topic3"); + logPojo.setTopicList(testTopicList); + assertEquals(testTopicList, logPojo.getTopicList()); + } + + @Test + public void testTransactionHash() { + String testTransactionHash = "abcdef1234567890abcdef1234567890abcdef12"; + logPojo.setTransactionHash(testTransactionHash); + assertEquals(testTransactionHash, logPojo.getTransactionHash()); + } + + @Test + public void testTransactionIndex() { + long testTransactionIndex = 3L; + logPojo.setTransactionIndex(testTransactionIndex); + assertEquals(testTransactionIndex, logPojo.getTransactionIndex()); + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java index 5ada5612fce..cf67ae4b087 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java @@ -93,6 +93,7 @@ public void TransferTokenTest() ECKey ecKey3 = new ECKey(Utils.getRandom()); List params = new ArrayList<>(); + logger.info("show db key: {}", StringUtil.createDbKey(ByteString.copyFrom("test".getBytes()))); params.add(StringUtil.encode58Check(ecKey1.getAddress())); params.add(StringUtil.encode58Check(ecKey2.getAddress())); params.add(StringUtil.encode58Check(ecKey3.getAddress())); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java b/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java index 8da6e4c96ea..172e3f17f1b 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java @@ -18,14 +18,22 @@ package org.tron.common.runtime.vm; +import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.tron.common.runtime.vm.DataWord.isZero; import java.math.BigInteger; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; import org.bouncycastle.util.encoders.Hex; +import org.eclipse.jetty.util.ArrayUtil; import org.junit.Test; +import org.tron.core.db.ByteArrayWrapper; @Slf4j public class DataWordTest { @@ -70,16 +78,16 @@ public void testAddPerformance() { DataWord x = new DataWord(one); x.add(x); } - System.out.println("Add1: " + (System.currentTimeMillis() - now1) + "ms"); + logger.info("Add1: " + (System.currentTimeMillis() - now1) + "ms"); long now2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { DataWord x = new DataWord(one); x.add2(x); } - System.out.println("Add2: " + (System.currentTimeMillis() - now2) + "ms"); + logger.info("Add2: " + (System.currentTimeMillis() - now2) + "ms"); } else { - System.out.println("ADD performance test is disabled."); + logger.info("ADD performance test is disabled."); } } @@ -90,11 +98,11 @@ public void testAdd2() { DataWord x = new DataWord(two); x.add(new DataWord(two)); - System.out.println(Hex.toHexString(x.getData())); + logger.info(Hex.toHexString(x.getData())); DataWord y = new DataWord(two); y.add2(new DataWord(two)); - System.out.println(Hex.toHexString(y.getData())); + logger.info(Hex.toHexString(y.getData())); } @Test @@ -107,12 +115,12 @@ public void testAdd3() { DataWord x = new DataWord(three); x.add(new DataWord(three)); assertEquals(32, x.getData().length); - System.out.println(Hex.toHexString(x.getData())); + logger.info(Hex.toHexString(x.getData())); // FAIL // DataWord y = new DataWord(three); // y.add2(new DataWord(three)); - // System.out.println(Hex.toHexString(y.getData())); + // logger.info(Hex.toHexString(y.getData())); } @Test @@ -128,8 +136,8 @@ public void testMod() { } two[31] = 0x56; // 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff56 - DataWord x = new DataWord(one);// System.out.println(x.value()); - DataWord y = new DataWord(two);// System.out.println(y.value()); + DataWord x = new DataWord(one);// logger.info(x.value()); + DataWord y = new DataWord(two);// logger.info(y.value()); y.mod(x); assertEquals(32, y.getData().length); assertEquals(expected, Hex.toHexString(y.getData())); @@ -143,8 +151,8 @@ public void testMul() { byte[] two = new byte[32]; two[11] = 0x1; // 0x0000000000000000000000010000000000000000000000000000000000000000 - DataWord x = new DataWord(one);// System.out.println(x.value()); - DataWord y = new DataWord(two);// System.out.println(y.value()); + DataWord x = new DataWord(one);// logger.info(x.value()); + DataWord y = new DataWord(two);// logger.info(y.value()); x.mul(y); assertEquals(32, y.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", @@ -160,8 +168,8 @@ public void testMulOverflow() { byte[] two = new byte[32]; two[0] = 0x1; // 0x1000000000000000000000000000000000000000000000000000000000000000 - DataWord x = new DataWord(one);// System.out.println(x.value()); - DataWord y = new DataWord(two);// System.out.println(y.value()); + DataWord x = new DataWord(one);// logger.info(x.value()); + DataWord y = new DataWord(two);// logger.info(y.value()); x.mul(y); assertEquals(32, y.getData().length); assertEquals("0100000000000000000000000000000000000000000000000000000000000000", @@ -226,8 +234,8 @@ public void testPow() { BigInteger result1 = x.modPow(x, y); BigInteger result2 = pow(x, y); - System.out.println(result1); - System.out.println(result2); + logger.info(result1.toString()); + logger.info(result2.toString()); } @Test @@ -238,7 +246,7 @@ public void testSignExtend1() { String expected = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -249,7 +257,7 @@ public void testSignExtend2() { String expected = "00000000000000000000000000000000000000000000000000000000000000f2"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -261,7 +269,7 @@ public void testSignExtend3() { String expected = "00000000000000000000000000000000000000000000000000000000000000ab"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -273,7 +281,7 @@ public void testSignExtend4() { String expected = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -285,7 +293,7 @@ public void testSignExtend5() { String expected = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -297,7 +305,7 @@ public void testSignExtend6() { String expected = "0000000000000000000000000000000000000000000000000000000002345678"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -309,7 +317,7 @@ public void testSignExtend7() { String expected = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffff82345678"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -322,7 +330,7 @@ public void testSignExtend8() { String expected = "0034567882345678823456788234567882345678823456788234567882345678"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -576,9 +584,39 @@ private void testShiftRightSigned(String[][] cases) { DataWord arg = new DataWord(c[1]); DataWord expected = new DataWord(c[2]); DataWord actual = value.shiftRightSigned(arg); - assertEquals(i + " " + Arrays.asList(c).toString(), expected, actual); + assertEquals(i + " " + Arrays.asList(c), expected, actual); } } + @Test + public void testIsZero() { + DataWord dataWord = new DataWord(new byte[0]); + DataWord d = new DataWord(new ByteArrayWrapper(new byte[0])); + assertTrue(d.isZero()); + d.negate(); + assertThrows(IllegalArgumentException.class, () -> new ByteArrayWrapper(null)); + assertTrue(dataWord.isZero()); + assertTrue(isZero(new byte[0])); + assertFalse(isZero(new byte[]{1})); + DataWord dataWord1 = new DataWord(new byte[]{0, 1}); + assertFalse(dataWord1.isZero()); + assertTrue(isNotEmpty(new DataWord((byte[]) null).getClonedData())); + assertTrue(isNotEmpty(dataWord1.getClonedData())); + logger.info(dataWord.toPrefixString()); + logger.info(dataWord1.toPrefixString()); + logger.info(new DataWord((new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8})).toPrefixString()); + logger.info(dataWord.shortHex()); + logger.info(DataWord.shortHex(new byte[0])); + logger.info(DataWord.bigIntValue(new byte[]{1})); + logger.info(dataWord.bigIntValue()); + logger.info("dataWord is Hex: {}", dataWord.isHex("test")); + logger.info(dataWord.asString()); + logger.info(Arrays.toString(dataWord.getNoEndZeroesData())); + DataWord tmp = dataWord; + assertEquals(dataWord, tmp); + assertNotEquals(dataWord, null); + assertEquals(-1, dataWord.compareTo(null)); + } + } diff --git a/framework/src/test/java/org/tron/common/utils/ALockTest.java b/framework/src/test/java/org/tron/common/utils/ALockTest.java new file mode 100644 index 00000000000..d4501756daa --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ALockTest.java @@ -0,0 +1,27 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertNotNull; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import org.junit.Before; +import org.junit.Test; + +public class ALockTest { + private ALock aLock; + private Lock mockLock; + + @Before + public void setUp() { + mockLock = new ReentrantLock(); + aLock = new ALock(mockLock); + } + + @Test + public void testLockAndUnlock() { + aLock.lock(); + assertNotNull(aLock); + aLock.close(); + } + +} diff --git a/framework/src/test/java/org/tron/common/utils/BIUtilTest.java b/framework/src/test/java/org/tron/common/utils/BIUtilTest.java new file mode 100644 index 00000000000..d126eb2a6b1 --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/BIUtilTest.java @@ -0,0 +1,155 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import org.junit.Test; + +public class BIUtilTest { + + @Test + public void testIsLessThan() { + BigInteger valueA = BigInteger.valueOf(1); + BigInteger valueB = BigInteger.valueOf(2); + assertTrue(BIUtil.isLessThan(valueA, valueB)); + + valueA = BigInteger.valueOf(3); + valueB = BigInteger.valueOf(3); + assertFalse(BIUtil.isLessThan(valueA, valueB)); + + valueA = BigInteger.valueOf(4); + valueB = BigInteger.valueOf(2); + assertFalse(BIUtil.isLessThan(valueA, valueB)); + } + + @Test + public void testIsZero() { + BigInteger value = BigInteger.ZERO; + assertTrue(BIUtil.isZero(value)); + + value = BigInteger.valueOf(1); + assertFalse(BIUtil.isZero(value)); + + value = BigInteger.valueOf(-1); + assertFalse(BIUtil.isZero(value)); + } + + @Test + public void testIsEqual() { + BigInteger valueA = BigInteger.valueOf(1); + BigInteger valueB = BigInteger.valueOf(1); + assertTrue(BIUtil.isEqual(valueA, valueB)); + + valueA = BigInteger.valueOf(2); + valueB = BigInteger.valueOf(3); + assertFalse(BIUtil.isEqual(valueA, valueB)); + } + + @Test + public void testIsNotEqual() { + BigInteger valueA = BigInteger.valueOf(1); + BigInteger valueB = BigInteger.valueOf(2); + assertTrue(BIUtil.isNotEqual(valueA, valueB)); + + valueA = BigInteger.valueOf(3); + valueB = BigInteger.valueOf(3); + assertFalse(BIUtil.isNotEqual(valueA, valueB)); + } + + @Test + public void testIsMoreThan() { + BigInteger valueA = BigInteger.valueOf(3); + BigInteger valueB = BigInteger.valueOf(2); + assertTrue(BIUtil.isMoreThan(valueA, valueB)); + + valueA = BigInteger.valueOf(1); + valueB = BigInteger.valueOf(2); + assertFalse(BIUtil.isMoreThan(valueA, valueB)); + + valueA = BigInteger.valueOf(2); + valueB = BigInteger.valueOf(2); + assertFalse(BIUtil.isMoreThan(valueA, valueB)); + } + + @Test + public void testSum() { + BigInteger valueA = BigInteger.valueOf(5); + BigInteger valueB = BigInteger.valueOf(7); + BigInteger expected = BigInteger.valueOf(12); + assertEquals(expected, BIUtil.sum(valueA, valueB)); + } + + @Test + public void testToBI_byteArray() { + byte[] data = {1, 0, 0, 0, 0, 0, 0, 1}; // BigInteger(128) + BigInteger expected = new BigInteger(1, data); + assertEquals(expected, BIUtil.toBI(data)); + } + + @Test + public void testToBI_long() { + long data = 123456789L; + BigInteger expected = BigInteger.valueOf(data); + assertEquals(expected, BIUtil.toBI(data)); + } + + @Test + public void testIsPositive() { + BigInteger value = BigInteger.valueOf(1); + assertTrue(BIUtil.isPositive(value)); + + value = BigInteger.ZERO; + assertFalse(BIUtil.isPositive(value)); + + value = BigInteger.valueOf(-1); + assertFalse(BIUtil.isPositive(value)); + } + + @Test + public void testIsNotCovers() { + BigInteger covers = BigInteger.valueOf(5); + BigInteger value = BigInteger.valueOf(10); + assertTrue(BIUtil.isNotCovers(covers, value)); + + covers = BigInteger.valueOf(10); + value = BigInteger.valueOf(5); + assertFalse(BIUtil.isNotCovers(covers, value)); + + covers = BigInteger.valueOf(10); + value = BigInteger.valueOf(10); + assertFalse(BIUtil.isNotCovers(covers, value)); + } + + @Test + public void testMax() { + BigInteger first = BigInteger.valueOf(5); + BigInteger second = BigInteger.valueOf(10); + assertEquals(second, BIUtil.max(first, second)); + + first = BigInteger.valueOf(15); + second = BigInteger.valueOf(10); + assertEquals(first, BIUtil.max(first, second)); + + first = BigInteger.valueOf(10); + second = BigInteger.valueOf(10); + assertEquals(first, BIUtil.max(first, second)); + } + + @Test + public void testAddSafely() { + int a = Integer.MAX_VALUE; + int b = 1; + int expected = Integer.MAX_VALUE; + assertEquals(expected, BIUtil.addSafely(a, b)); + + a = Integer.MAX_VALUE - 1; + b = 2; + assertEquals(expected, BIUtil.addSafely(a, b)); + + a = 1; + expected = 3; + assertEquals(expected, BIUtil.addSafely(a, b)); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ByteArrayMapTest.java b/framework/src/test/java/org/tron/common/utils/ByteArrayMapTest.java new file mode 100644 index 00000000000..8abdc3e3def --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ByteArrayMapTest.java @@ -0,0 +1,145 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.mchange.v2.collection.MapEntry; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.junit.Before; +import org.junit.Test; +import org.tron.core.db.ByteArrayWrapper; + +public class ByteArrayMapTest { + + private ByteArrayMap byteArrayMap; + + @Before + public void setUp() { + byteArrayMap = new ByteArrayMap<>(); + } + + @Test + public void testPutAndGet() { + byte[] key = "key1".getBytes(); + String value = "value1"; + byteArrayMap.put(key, value); + assertEquals("Should return the correct value", value, byteArrayMap.get(key)); + } + + @Test + public void testSize() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + assertEquals("Should return the correct size", 2, byteArrayMap.size()); + } + + @Test + public void testRemove() { + byte[] key = "key".getBytes(); + String value = "value"; + byteArrayMap.put(key, value); + byteArrayMap.remove(key); + assertNull("Should return null after removal", byteArrayMap.get(key)); + } + + @Test + public void testContainsKey() { + byte[] key = "key".getBytes(); + byteArrayMap.put(key, "value"); + assertTrue("Should contain the key", byteArrayMap.containsKey(key)); + } + + @Test + public void testPutAll() { + Map mapToPut = createTestMap(); + byteArrayMap.putAll(mapToPut); + assertEquals("Should contain all entries after putAll", 2, byteArrayMap.size()); + assertEquals("Should return the correct value for key1", + "value1", byteArrayMap.get("key1".getBytes())); + assertEquals("Should return the correct value for key2", + "value2", byteArrayMap.get("key2".getBytes())); + + } + + @Test + public void testClear() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + assertFalse(byteArrayMap.isEmpty()); + byteArrayMap.clear(); + } + + @Test + public void testKeySet() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + Set set = byteArrayMap.keySet(); + assertTrue("Key set should contain key1", set.contains(key1)); + assertTrue("Key set should contain key2", set.contains(key2)); + } + + @Test + public void testValues() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + Collection values = byteArrayMap.values(); + assertTrue("Values should contain value1", values.contains("value1")); + assertTrue("Values should contain value1", byteArrayMap.containsValue("value1")); + assertTrue("Values should contain value2", values.contains("value2")); + } + + @Test + public void testEntrySet() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + Set> entrySet = byteArrayMap.entrySet(); + assertFalse(entrySet.isEmpty()); + assertEquals("Entry set size should be 2", 2, entrySet.size()); + assertThrows(Exception.class, () -> entrySet.contains(new Object())); + assertThrows(Exception.class, entrySet::toArray); + assertThrows(Exception.class, () -> entrySet.toArray(new Map.Entry[0])); + assertThrows(Exception.class, () -> entrySet.add(new MapEntry(key1, "value1"))); + assertThrows(Exception.class, () -> entrySet.remove(new MapEntry(key1, "value1"))); + assertThrows(Exception.class, () -> entrySet.containsAll(new HashSet<>())); + assertThrows(Exception.class, () -> entrySet.removeAll(new HashSet<>())); + assertThrows(Exception.class, () -> entrySet.addAll(new HashSet<>())); + assertThrows(Exception.class, () -> entrySet.retainAll(new HashSet<>())); + assertThrows(Exception.class, entrySet::clear); + } + + // Helper method to create a map for testing putAll + private Map createTestMap() { + Map map = new ByteArrayMap<>(); + map.put("key1".getBytes(), "value1"); + map.put("key2".getBytes(), "value2"); + return map; + } + + + @Test + public void test() { + Map map = new ByteArrayMap<>(); + Map testMap = createTestMap(); + assertNotEquals(map, testMap); + assertTrue(testMap.hashCode() <= 0); + assertNotNull(testMap.toString()); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ByteArraySetTest.java b/framework/src/test/java/org/tron/common/utils/ByteArraySetTest.java new file mode 100644 index 00000000000..22695f713a7 --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ByteArraySetTest.java @@ -0,0 +1,143 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import org.junit.Before; +import org.junit.Test; + +public class ByteArraySetTest { + + private ByteArraySet byteArraySet; + + @Before + public void setUp() { + byteArraySet = new ByteArraySet(); + } + + @Test + public void testSizeIsEmptyInitially() { + assertEquals(0, byteArraySet.size()); + } + + @Test + public void testIsEmptyInitially() { + assertTrue(byteArraySet.isEmpty()); + } + + @Test + public void testAddAndGetSize() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + assertEquals(1, byteArraySet.size()); + + byteArraySet.add(bytes2); + assertEquals(2, byteArraySet.size()); + } + + @Test + public void testContains() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + assertTrue(byteArraySet.contains(bytes1)); + assertFalse(byteArraySet.contains(bytes2)); + + byteArraySet.add(bytes2); + assertTrue(byteArraySet.contains(bytes2)); + + assertThrows(Exception.class, () -> byteArraySet.containsAll(new HashSet<>())); + assertThrows(Exception.class, () -> byteArraySet.retainAll(new HashSet<>())); + assertThrows(Exception.class, () -> byteArraySet.removeAll(new HashSet<>())); + assertThrows(Exception.class, () -> byteArraySet.equals(new ByteArraySet())); + assertThrows(Exception.class, () -> byteArraySet.hashCode()); + } + + @Test + public void testIterator() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + + Iterator iterator = byteArraySet.iterator(); + + assertTrue(iterator.hasNext()); + assertArrayEquals(bytes1, iterator.next()); + + assertTrue(iterator.hasNext()); + assertArrayEquals(bytes2, iterator.next()); + + assertFalse(iterator.hasNext()); + } + + @Test + public void testToArray() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + + byte[][] array = byteArraySet.toArray(new byte[0][]); + + assertEquals(2, array.length); + assertArrayEquals(bytes1, array[0]); + assertArrayEquals(bytes2, array[1]); + } + + @Test + public void testAddAll() { + List list = Arrays.asList( + new byte[]{1, 2, 3}, + new byte[]{4, 5, 6} + ); + + boolean result = byteArraySet.addAll(list); + + assertTrue(result); + assertEquals(2, byteArraySet.size()); + assertTrue(byteArraySet.contains(new byte[]{1, 2, 3})); + assertTrue(byteArraySet.contains(new byte[]{4, 5, 6})); + } + + @Test + public void testRemove() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + + boolean result = byteArraySet.remove(bytes1); + + assertTrue(result); + assertEquals(1, byteArraySet.size()); + assertFalse(byteArraySet.contains(bytes1)); + assertTrue(byteArraySet.contains(bytes2)); + } + + @Test + public void testClear() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + assertTrue(byteArraySet.size() > 0); + + byteArraySet.clear(); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java b/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java index 226b00b8cb1..c0db8c4b418 100644 --- a/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java +++ b/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java @@ -17,6 +17,12 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.ByteArray.fromHex; +import static org.tron.common.utils.ByteArray.jsonHexToInt; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; @@ -80,4 +86,33 @@ public void test2ToHexString() { assertEquals("ByteArray.toHexString is not equals Hex.toHexString", ByteArray.toHexString(bss), Hex.toHexString(bss)); } + + @Test + public void testFromObject_SerializableObject() { + String testString = "Hello, World!"; + byte[] result = ByteArray.fromObject(testString); + assertNotNull(result); + assertTrue(result.length > 0); + } + + @Test + public void testJsonHexToInt_ValidHex() { + try { + int result = jsonHexToInt("0x1A"); + assertEquals(26, result); + } catch (Exception e) { + fail("Exception should not have been thrown for valid hex string."); + } + assertThrows(Exception.class, () -> ByteArray.jsonHexToInt("1A")); + } + + @Test + public void testFromHexWithPrefix() { + String input = "0x1A3F"; + String expected = "1A3F"; + String result = fromHex(input); + assertEquals(expected, result); + String input1 = "1A3"; + assertEquals("01A3", fromHex(input1)); + } } diff --git a/framework/src/test/java/org/tron/common/utils/CollectionUtilsTest.java b/framework/src/test/java/org/tron/common/utils/CollectionUtilsTest.java new file mode 100644 index 00000000000..8b8ef35fb4b --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/CollectionUtilsTest.java @@ -0,0 +1,81 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import org.junit.Test; + +public class CollectionUtilsTest { + + @Test + public void testCollectList() { + List numbers = Arrays.asList("1", "2", "3"); + Function toInt = Integer::parseInt; + List integers = CollectionUtils.collectList(numbers, toInt); + assertEquals(Arrays.asList(1, 2, 3), integers); + } + + @Test + public void testCollectSet() { + List numbers = Arrays.asList("1", "2", "2", "3"); + Function toInt = Integer::parseInt; + Set integers = CollectionUtils.collectSet(numbers, toInt); + assertEquals(new HashSet<>(Arrays.asList(1, 2, 3)), integers); + } + + @Test + public void testTruncate() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List truncated = CollectionUtils.truncate(numbers, 3); + assertEquals(Arrays.asList(1, 2, 3), truncated); + } + + @Test + public void testTruncateNoLimit() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List truncated = CollectionUtils.truncate(numbers, 10); + assertEquals(numbers, truncated); + } + + @Test + public void testTruncateRandom() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List numbers1 = Arrays.asList(1, 2); + List truncated = CollectionUtils.truncateRandom(numbers, 3, 2); + List truncated1 = CollectionUtils.truncateRandom(numbers1, 3, 2); + assertEquals(2, truncated1.size()); + assertEquals(3, truncated.size()); + assertTrue(truncated.containsAll(Arrays.asList(1, 2, 3, 4, 5).subList(0, 2))); + // Last element could be 3, 4, or 5, so we just check that it's one of them + assertTrue(truncated.contains(3) || truncated.contains(4) || truncated.contains(5)); + } + + @Test + public void testTruncateRandomConfirmEqualLimit() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List truncated = CollectionUtils.truncateRandom(numbers, 5, 5); + assertEquals(numbers, truncated); + } + + @Test + public void testSelectList() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + Predicate isEven = n -> n % 2 == 0; + List selected = CollectionUtils.selectList(numbers, isEven); + assertEquals(Arrays.asList(2, 4), selected); + } + + @Test + public void testSelectSet() { + List numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); + Predicate isEven = n -> n % 2 == 0; + Set selected = CollectionUtils.selectSet(numbers, isEven); + assertEquals(new HashSet<>(Arrays.asList(2, 4)), selected); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/FileUtilTest.java b/framework/src/test/java/org/tron/common/utils/FileUtilTest.java index 9aff1566ef3..126e0918520 100644 --- a/framework/src/test/java/org/tron/common/utils/FileUtilTest.java +++ b/framework/src/test/java/org/tron/common/utils/FileUtilTest.java @@ -1,11 +1,88 @@ package org.tron.common.utils; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.tron.common.utils.FileUtil.readData; + import java.io.File; +import java.io.FileWriter; import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; public class FileUtilTest { + private Path tempDir; + + @Before + public void setUp() throws IOException { + tempDir = Files.createTempDirectory("testDir"); + + Files.createFile(tempDir.resolve("file1.txt")); + Files.createFile(tempDir.resolve("file2.txt")); + + Path subDir = Files.createDirectory(tempDir.resolve("subdir")); + Files.createFile(subDir.resolve("file3.txt")); + } + + @After + public void tearDown() throws IOException { + Files.walk(tempDir) + .sorted(Comparator.reverseOrder()) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + + @Test + public void testRecursiveList() throws IOException { + List files = FileUtil.recursiveList(tempDir.toString()); + + assertTrue(files.contains(tempDir.resolve("file1.txt").toString())); + assertTrue(files.contains(tempDir.resolve("file2.txt").toString())); + assertTrue(files.contains(tempDir.resolve("subdir").resolve("file3.txt").toString())); + + assertEquals(3, files.size()); + } + + @Test + public void testReadData_NormalFile() throws IOException { + Path tempFile = Files.createTempFile("testfile", ".txt"); + try (FileWriter writer = new FileWriter(tempFile.toFile())) { + writer.write("Hello, World!"); + } + + char[] buffer = new char[1024]; + int len = readData(tempFile.toString(), buffer); + + assertEquals(13, len); + assertArrayEquals("Hello, World!".toCharArray(), Arrays.copyOf(buffer, 13)); + } + + @Test + public void testReadData_IOException() { + char[] buffer = new char[1024]; + File dir = new File(System.getProperty("java.io.tmpdir")); + int len = readData(dir.getAbsolutePath(), buffer); + assertEquals(0, len); + } + @Test public void testCreateFileIfNotExists() { @@ -16,15 +93,15 @@ public void testCreateFileIfNotExists() { } catch (IOException e) { System.out.println("ignore this exception."); } - Assert.assertTrue(file1.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(existFile)); - Assert.assertTrue(file1.exists()); + assertTrue(file1.exists()); + assertTrue(FileUtil.createDirIfNotExists(existFile)); + assertTrue(file1.exists()); String notExistFile = "notexistsfile.txt"; File file2 = new File(notExistFile); - Assert.assertTrue(!file2.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(notExistFile)); - Assert.assertTrue(file2.exists()); + assertTrue(!file2.exists()); + assertTrue(FileUtil.createDirIfNotExists(notExistFile)); + assertTrue(file2.exists()); file1.delete(); file2.delete(); } @@ -34,16 +111,18 @@ public void testCreateDirIfNotExists() { String existDir = "existsdir"; File fileDir1 = new File(existDir); fileDir1.mkdir(); - Assert.assertTrue(fileDir1.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(existDir)); - Assert.assertTrue(fileDir1.exists()); + assertTrue(fileDir1.exists()); + assertTrue(FileUtil.createDirIfNotExists(existDir)); + assertTrue(fileDir1.exists()); String notExistDir = "notexistsdir"; File fileDir2 = new File(notExistDir); - Assert.assertTrue(!fileDir2.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(notExistDir)); - Assert.assertTrue(fileDir2.exists()); + assertTrue(!fileDir2.exists()); + assertTrue(FileUtil.createDirIfNotExists(notExistDir)); + assertTrue(fileDir2.exists()); fileDir1.delete(); fileDir2.delete(); } + + } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java b/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java index 9a4efb722e3..8681ff58270 100644 --- a/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java +++ b/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java @@ -1,7 +1,13 @@ package org.tron.common.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.JsonUtil.json2Obj; +import static org.tron.common.utils.JsonUtil.obj2Json; + import lombok.Data; -import org.junit.Assert; import org.junit.Test; public class JsonUtilTest { @@ -25,11 +31,50 @@ public void test() { a1.setKey("abc"); a1.setValue(100); - String jsonString = JsonUtil.obj2Json(a1); + String jsonString = obj2Json(a1); A a2 = JsonUtil.json2Obj(jsonString, A.class); - Assert.assertEquals(a2.getKey(), "abc"); - Assert.assertEquals(a2.getValue(), 100); + assert a2 != null; + assertEquals("abc", a2.getKey()); + assertEquals(100, a2.getValue()); + assertNull(obj2Json(null)); + assertNull(json2Obj(null, null)); + + + } + + @Test + public void testObj2JsonWithCircularReference() { + Node node1 = new Node("Node1"); + Node node2 = new Node("Node2"); + node1.setNext(node2); + node2.setNext(node1); + + try { + obj2Json(node1); + fail("Expected a RuntimeException to be thrown"); + } catch (RuntimeException e) { + assertTrue(e.getCause() instanceof com.fasterxml.jackson.databind.JsonMappingException); + } + } + + @Test(expected = RuntimeException.class) + public void testInvalidJson() { + String invalidJson = "{invalid: json}"; + json2Obj(invalidJson, String.class); + } + + class Node { + private String name; + private org.tron.common.utils.JsonUtilTest.Node next; + + public Node(String name) { + this.name = name; + } + + public void setNext(org.tron.common.utils.JsonUtilTest.Node next) { + this.next = next; + } } } diff --git a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java index 7bc922661cb..4de441d940d 100644 --- a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java +++ b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java @@ -1,19 +1,42 @@ package org.tron.common.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.beust.jcommander.internal.Lists; import com.google.protobuf.ByteString; +import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; +import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.tron.core.capsule.WitnessCapsule; @Slf4j -@Ignore public class RandomGeneratorTest { + private RandomGenerator randomGenerator; + + @Before + public void setUp() { + randomGenerator = new RandomGenerator<>(); + } + + @Test + public void testShufflePreservesElements() { + List list = Arrays.asList(1, 2, 3, 4, 5); + List shuffledList = randomGenerator.shuffle(list, System.currentTimeMillis()); + + assertEquals(list.size(), shuffledList.size()); + for (Integer num : list) { + assertTrue(shuffledList.contains(num)); + } + } + + @Ignore @Test public void shuffle() { final List witnessCapsuleListBefore = this.getWitnessList(); diff --git a/framework/src/test/java/org/tron/common/utils/SetAdapterTest.java b/framework/src/test/java/org/tron/common/utils/SetAdapterTest.java new file mode 100644 index 00000000000..1d53ea3dd1a --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/SetAdapterTest.java @@ -0,0 +1,114 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.junit.Before; +import org.junit.Test; + +public class SetAdapterTest { + + private Map delegate; + private SetAdapter setAdapter; + + @Before + public void setUp() { + delegate = new HashMap<>(); + setAdapter = new SetAdapter<>(delegate); + } + + @Test + public void testSizeInitiallyEmpty() { + assertEquals(0, setAdapter.size()); + } + + @Test + public void testIsEmptyInitially() { + assertTrue(setAdapter.isEmpty()); + } + + @Test + public void testContainsWhenEmpty() { + assertFalse(setAdapter.contains("test")); + } + + @Test + public void testAddAndGetSize() { + setAdapter.add("one"); + assertEquals(1, setAdapter.size()); + } + + @Test + public void testAddAndCheckContains() { + setAdapter.add("two"); + assertTrue(setAdapter.contains("two")); + } + + @Test + public void testRemoveAndCheckContains() { + setAdapter.add("three"); + assertTrue(setAdapter.contains("three")); + setAdapter.remove("three"); + assertFalse(setAdapter.contains("three")); + } + + @Test + public void testIterator() { + setAdapter.add("four"); + setAdapter.add("five"); + Set expected = new HashSet<>(Arrays.asList("four", "five")); + Set actual = new HashSet<>(setAdapter); // Convert to HashSet to ignore order + assertEquals(expected, actual); + } + + @Test + public void testToArray() { + setAdapter.add("six"); + setAdapter.add("seven"); + Object[] array = setAdapter.toArray(); + Arrays.sort(array); // Sorting to ignore order + assertArrayEquals(new String[]{"seven", "six"}, array); + } + + @Test + public void testToArrayWithGivenType() { + setAdapter.add("eight"); + String[] array = setAdapter.toArray(new String[0]); + Arrays.sort(array); // Sorting to ignore order + assertArrayEquals(new String[]{"eight"}, array); + } + + @Test + public void testAddAll() { + setAdapter.addAll(Arrays.asList("nine", "ten")); + assertTrue(setAdapter.containsAll(Arrays.asList("nine", "ten"))); + } + + @Test + public void testRemoveAll() { + setAdapter.addAll(Arrays.asList("eleven", "twelve")); + setAdapter.removeAll(Collections.singletonList("eleven")); + assertFalse(setAdapter.contains("eleven")); + assertTrue(setAdapter.contains("twelve")); + } + + @Test + public void testClear() { + setAdapter.addAll(Arrays.asList("thirteen", "fourteen")); + setAdapter.clear(); + assertTrue(setAdapter.isEmpty()); + } + + @Test(expected = RuntimeException.class) + public void testRetainAllThrowsException() { + setAdapter.retainAll(Collections.emptyList()); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java index 51745e96e92..0df72cc125d 100644 --- a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java +++ b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java @@ -1,8 +1,19 @@ package org.tron.common.utils; +import static java.nio.file.Files.createTempFile; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import ch.qos.logback.core.util.FileUtil; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; +import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import org.tron.common.parameter.CommonParameter; @@ -10,18 +21,37 @@ public class Sha256HashTest { @Test - public void testHash() { + public void testHash() throws IOException { //Example from https://github.com/tronprotocol/tips/blob/master/TWP-001.md byte[] input = ByteArray.fromHexString("A0E11973395042BA3C0B52B4CDF4E15EA77818F275"); byte[] hash0 = Sha256Hash.hash(CommonParameter .getInstance().isECKeyCryptoEngine(), input); byte[] hash1 = Sha256Hash.hash(CommonParameter .getInstance().isECKeyCryptoEngine(), hash0); - Assert.assertEquals(Arrays.toString(hash0), Arrays.toString(ByteArray + assertEquals(Arrays.toString(hash0), Arrays.toString(ByteArray .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084"))); - Assert.assertEquals(Arrays.toString(hash1), Arrays.toString(ByteArray + assertEquals(Arrays.toString(hash1), Arrays.toString(ByteArray .fromHexString("10AE21E887E8FE30C591A22A5F8BB20EB32B2A739486DC5F3810E00BBDB58C5C"))); + Sha256Hash sha256Hash = new Sha256Hash(1, new byte[32]); + assertNotNull(sha256Hash.toBigInteger()); + + Sha256Hash.create(true, ("byte1-1").getBytes(StandardCharsets.UTF_8)); + File testfile = createTempFile("testfile", ".txt").toFile(); + Sha256Hash.of(true, testfile); + Sha256Hash.createDouble(true, new byte[0]); + Sha256Hash.twiceOf(true, new byte[0]); + Sha256Hash.hashTwice(true, new byte[0]); + Sha256Hash.hashTwice(false, new byte[0]); + Sha256Hash.hashTwice(true, new byte[0], 0, 0); + Sha256Hash.hashTwice(false, new byte[0], 0, 0); + Sha256Hash.hash(false, new byte[0], 0, 0); + Sha256Hash.hashTwice(true, new byte[0], 0, 0, new byte[0], 0, 0); + Sha256Hash.hashTwice(false, new byte[0], 0, 0, new byte[0], 0, 0); + assertTrue(testfile.delete()); + + + } @Test @@ -51,7 +81,7 @@ public void testMultiThreadingHash() { e.printStackTrace(); } }); - Assert.assertEquals(70000, countAll.get()); - Assert.assertEquals(0, countFailed.get()); + assertEquals(70000, countAll.get()); + assertEquals(0, countFailed.get()); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/utils/SlidingWindowCounterTest.java b/framework/src/test/java/org/tron/common/utils/SlidingWindowCounterTest.java new file mode 100644 index 00000000000..016b7ac611b --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/SlidingWindowCounterTest.java @@ -0,0 +1,63 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Before; +import org.junit.Test; + +public class SlidingWindowCounterTest { + + private SlidingWindowCounter counter; + + @Before + public void setUp() { + counter = new SlidingWindowCounter(3); + } + + @Test + public void testIncrease() { + counter.increase(); + counter.increase(); + counter.increase(); + assertEquals(3, counter.totalCount()); + counter.resizeWindow(5); + assertNotNull(counter.toString()); + } + + @Test + public void testTotalAndAdvance() { + counter.increase(); + counter.increase(); + counter.advance(); + counter.increase(); + int total = counter.totalAndAdvance(); + assertEquals(3, total); + assertEquals(3, counter.totalCount()); + } + + @Test + public void testTotalCount() { + counter.increase(); + counter.increase(); + counter.advance(); + assertEquals(2, counter.totalCount()); + } + + @Test + public void testCircularWindow() { + for (int i = 0; i < 3; i++) { + counter.increase(); + } + counter.increase(); + counter.advance(); + assertEquals(4, counter.totalCount()); + + counter.increase(); + counter.increase(); + counter.increase(); + int total = counter.totalAndAdvance(); + assertEquals(7, total); + assertEquals(7, counter.totalCount()); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java b/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java index b9188e96060..c98115af3f0 100644 --- a/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java +++ b/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java @@ -17,9 +17,13 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.tron.common.utils.TypeConversion.bytesToHexString; import static org.tron.common.utils.TypeConversion.bytesToLong; import static org.tron.common.utils.TypeConversion.hexStringToBytes; +import static org.tron.common.utils.TypeConversion.increment; import static org.tron.common.utils.TypeConversion.longToBytes; import lombok.extern.slf4j.Slf4j; @@ -58,6 +62,14 @@ public void testHexStringToBytes() { //logger.info("hex string 7f to bytes is: {}", result); byte[] expected = new byte[]{127}; assertArrayEquals(expected, result); + assertNull(hexStringToBytes("test")); + } + @Test + public void testIncrementNormalCase() { + byte[] bytes = {1, 2, 3}; + boolean result = increment(bytes); + assertTrue(result); + assertArrayEquals(new byte[]{1, 2, 4}, bytes); } } diff --git a/framework/src/test/java/org/tron/common/utils/UtilsTest.java b/framework/src/test/java/org/tron/common/utils/UtilsTest.java new file mode 100644 index 00000000000..6a593a7684f --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/UtilsTest.java @@ -0,0 +1,74 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.nio.charset.Charset; +import java.security.SecureRandom; +import org.junit.Test; + +public class UtilsTest { + + @Test + public void testGetRandom() { + SecureRandom random = Utils.getRandom(); + assertNotNull("SecureRandom should not be null", random); + } + + @Test + public void testGetBytes() { + char[] chars = "hello".toCharArray(); + byte[] bytes = Utils.getBytes(chars); + + // Convert back to String to check if it's the same + String result = new String(bytes, Charset.forName("UTF-8")); + assertEquals("Converted bytes should match the original string", "hello", result); + } + + @Test + public void testGetIdShort() { + String longId = "12345678901234567890"; + String shortId = Utils.getIdShort(longId); + assertEquals("Short ID should be the first 8 characters of the long ID", "12345678", shortId); + + String nullId = Utils.getIdShort(null); + assertEquals("ID should be '' for null input", "", nullId); + } + + @Test + public void testClone() { + byte[] original = {1, 2, 3, 4, 5}; + byte[] clone = Utils.clone(original); + + assertArrayEquals("Clone should be equal to the original", original, clone); + + // Modify the clone to ensure it's a new array + clone[0] = 99; + assertNotEquals("Modifying the clone should not affect the original", original[0], clone[0]); + } + + @Test + public void testAlignLeft() { + String result = Utils.align("abc", '-', 10, false); + String result1 = Utils.align("abc", '-', 2, false); + assertEquals("abc-------", result); + assertEquals("abc", result1); + } + + @Test + public void testAlignRight() { + String result = Utils.align("abc", '-', 10, true); + assertEquals("-------abc", result); + } + + @Test + public void testRepeat() { + String result = Utils.repeat("a", 5); + assertEquals("aaaaa", result); + + result = Utils.repeat("abc", 3); + assertEquals("abcabcabc", result); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ValueTest.java b/framework/src/test/java/org/tron/common/utils/ValueTest.java new file mode 100644 index 00000000000..f7e4f415f5f --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ValueTest.java @@ -0,0 +1,198 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.tron.common.utils.ByteUtil.EMPTY_BYTE_ARRAY; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Before; +import org.junit.Test; + +public class ValueTest { + + private Value value; + + @Before + public void setUp() { + value = new Value(); + value.init(new byte[100]); + } + + @Test + public void testAsObj() { + Object obj = new Object(); + value = new Value(obj); + assertEquals("asObj should return the encapsulated object", obj, value.asObj()); + } + + @Test + public void testAsList() { + Object[] array = { "element1", "element2" }; + value = new Value(array); + List list = value.asList(); + assertEquals(2, list.size()); + assertEquals("element1", list.get(0)); + } + + @Test + public void testAsInt() { + value = new Value(123); + assertEquals(123, value.asInt()); + assertEquals(0, new Value(new byte[0]).asInt()); + assertEquals(0, new Value("test").asInt()); + } + + @Test + public void testAsLong() { + value = new Value(123456789L); + assertEquals(123456789L, value.asLong()); + assertEquals(0L, new Value(new byte[0]).asLong()); + assertEquals(0L, new Value("TEST").asLong()); + } + + @Test + public void testAsBigInt() { + BigInteger bigInteger = new BigInteger("12345678901234567890"); + value = new Value(bigInteger); + assertEquals(bigInteger, value.asBigInt()); + } + + @Test + public void testAsString() { + value = new Value("test string"); + assertEquals("test string", value.asString()); + assertNotNull(new Value(new byte[0]).asString()); + assertEquals("", new Value(100).asString()); + assertNotNull(value.get(0)); + + } + + @Test + public void testAsBytes() { + byte[] bytes = { 0x01, 0x02, 0x03 }; + value = new Value(bytes); + assertArrayEquals("asBytes should return the correct byte array", bytes, value.asBytes()); + assertEquals(EMPTY_BYTE_ARRAY, new Value(100).asBytes()); + } + + @Test + public void testGet() { + List list = Arrays.asList("element1", "element2"); + value = new Value(list.toArray()); + Value element = value.get(0); + assertEquals("element1", element.asString()); + assertNotNull(value.get(2)); + } + + @Test(expected = Exception.class) + public void testGetNegativeIndex() { + value = new Value(new Object[] { "element1", "element2" }); + value.get(-1); + } + + @Test + public void testCmp() { + Value value1 = new Value("test"); + Value value2 = new Value("test"); + assertTrue("cmp should return true for equal values", value1.cmp(value2)); + } + + @Test + public void testIsList() { + value = new Value(new Object[] { "element1", "element2" }); + assertTrue("isList should return true for an array", value.isList()); + assertNotNull(value.toString()); + } + + @Test + public void testIsString() { + value = new Value("test string"); + assertTrue("isString should return true for a string", value.isString()); + } + + @Test + public void testIsInt() { + value = new Value(123); + assertTrue("isInt should return true for an integer", value.isInt()); + } + + @Test + public void testIsLong() { + value = new Value(123456789L); + assertTrue("isLong should return true for a long", value.isLong()); + } + + @Test + public void testIsBigInt() { + value = new Value(new BigInteger("12345678901234567890")); + assertTrue("isBigInt should return true for a BigInteger", value.isBigInt()); + } + + @Test + public void testIsBytes() { + byte[] bytes = { 0x01, 0x02, 0x03 }; + value = new Value(bytes); + assertTrue("isBytes should return true for a byte array", value.isBytes()); + } + + @Test + public void testIsReadableString() { + byte[] readableBytes = "Hello World".getBytes(); + value = new Value(readableBytes); + assertTrue(value.isReadableString()); + } + + @Test + public void testIsHexString() { + byte[] hexBytes = Hex.decode("48656c6c6f20576f726c64"); + value = new Value(hexBytes); + assertFalse("isHexString should return true for hex byte array", value.isHexString()); + } + + @Test + public void testIsHashCode() { + byte[] hashBytes = new byte[32]; + value = new Value(hashBytes); + assertTrue("isHashCode should return true for a 32 byte array", value.isHashCode()); + } + + @Test + public void testIsNull() { + value = new Value(null); + assertTrue("isNull should return true for null", value.isNull()); + } + + @Test + public void testIsEmpty() { + value = new Value(""); + assertTrue("isEmpty should return true for an empty string", value.isEmpty()); + } + + @Test + public void testLength() { + value = new Value("test string"); + assertEquals(11, value.length()); + } + + @Test + public void testToString() { + value = new Value("test string"); + assertEquals("test string", value.toString()); + } + + @Test + public void testCountBranchNodes() { + Object[] array = { new Value("element1"), new Value("element2") }; + value = new Value(array); + assertEquals(0, value.countBranchNodes()); + value = new Value(new byte[0]); + assertEquals(0, value.countBranchNodes()); + + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java index ee872be6330..5a085e16ca6 100644 --- a/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java @@ -4234,10 +4234,8 @@ public static HttpResponse sendShieldCoinWithoutAsk( public static void freedResource( String httpNode, byte[] fromAddress, byte[] toAddress, String fromKey) { long balance = HttpMethed.getBalance(httpNode, fromAddress); - // System.out.println("剩余资源:" + balance); sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); balance = HttpMethed.getBalance(httpNode, fromAddress); - // System.out.println("之后资源:" + balance); } /** constructor. */ diff --git a/framework/src/test/java/org/tron/common/zksnark/ZksnarkClientTest.java b/framework/src/test/java/org/tron/common/zksnark/ZksnarkClientTest.java new file mode 100644 index 00000000000..21275d548a0 --- /dev/null +++ b/framework/src/test/java/org/tron/common/zksnark/ZksnarkClientTest.java @@ -0,0 +1,43 @@ +package org.tron.common.zksnark; + +import static org.junit.Assert.assertThrows; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.contract.BalanceContract; + +public class ZksnarkClientTest { + + public ZksnarkClient zksnarkClient; + + @Before + public void setUp() { + zksnarkClient = ZksnarkClient.getInstance(); + } + + @Test + public void testCheckZksnarkProof() { + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + Transaction transaction = Transaction.newBuilder().setRawData(Transaction.raw.newBuilder() + .setData(ByteString.copyFrom("transfer".getBytes(StandardCharsets.UTF_8))) + .addContract(Transaction.Contract.newBuilder().setParameter(Any.pack(transferContract)) + .setType(Transaction.Contract.ContractType.TransferContract))) + .addRet(Transaction.Result.newBuilder().setAssetIssueID("1234567").build()).build(); + byte[] b = ByteArray + .fromHexString("ded9c2181fd7ea468a7a7b1475defe90bb0fc0ca8d0f2096b0617465cea6568c"); + assertThrows(StatusRuntimeException.class, () -> zksnarkClient.checkZksnarkProof(transaction, b, + 10000L)); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/CoreExceptionTest.java b/framework/src/test/java/org/tron/core/CoreExceptionTest.java new file mode 100644 index 00000000000..89feaba338c --- /dev/null +++ b/framework/src/test/java/org/tron/core/CoreExceptionTest.java @@ -0,0 +1,1161 @@ +package org.tron.core; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; +import static org.tron.core.exception.BadBlockException.TypeEnum.DEFAULT; +import static org.tron.core.exception.P2pException.TypeEnum.NO_SUCH_MESSAGE; +import static org.tron.core.exception.P2pException.TypeEnum.PARSE_MESSAGE_FAILED; +import static org.tron.core.exception.P2pException.TypeEnum.SYNC_FAILED; + +import org.junit.Test; +import org.tron.common.error.TronDBException; +import org.tron.core.exception.AccountResourceInsufficientException; +import org.tron.core.exception.BadBlockException; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.BadNumberBlockException; +import org.tron.core.exception.BadTransactionException; +import org.tron.core.exception.BalanceInsufficientException; +import org.tron.core.exception.CancelException; +import org.tron.core.exception.CipherException; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractSizeNotEqualToOneException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.EventBloomException; +import org.tron.core.exception.HeaderNotFound; +import org.tron.core.exception.HighFreqException; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.JsonRpcInternalException; +import org.tron.core.exception.JsonRpcInvalidParamsException; +import org.tron.core.exception.JsonRpcInvalidRequestException; +import org.tron.core.exception.JsonRpcMethodNotFoundException; +import org.tron.core.exception.JsonRpcTooManyResultException; +import org.tron.core.exception.NonCommonBlockException; +import org.tron.core.exception.NonUniqueObjectException; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.PermissionException; +import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.RevokingStoreIllegalStateException; +import org.tron.core.exception.SignatureFormatException; +import org.tron.core.exception.StoreException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TooBigTransactionResultException; +import org.tron.core.exception.TraitorPeerException; +import org.tron.core.exception.TransactionExpirationException; +import org.tron.core.exception.TronRuntimeException; +import org.tron.core.exception.TypeMismatchNamingException; +import org.tron.core.exception.UnLinkedBlockException; +import org.tron.core.exception.UnReachBlockException; +import org.tron.core.exception.VMIllegalException; +import org.tron.core.exception.ValidateScheduleException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.exception.ZkProofValidateException; +import org.tron.core.exception.ZksnarkException; + +public class CoreExceptionTest { + + @Test + public void testAccountResourceInsufficientExceptionMessage() { + String expectedMessage = "Account resources are insufficient"; + AccountResourceInsufficientException exception = + new AccountResourceInsufficientException(expectedMessage); + + assertEquals(expectedMessage, exception.getMessage()); + } + + @Test + public void testBadBlockExceptionWithNoMessageAndDefaultType() { + BadBlockException exception = new BadBlockException(); + + assertNull(exception.getMessage()); + + assertEquals(DEFAULT, exception.getType()); + } + + @Test + public void testBadBlockExceptionWithMessageAndDefaultType() { + String testMessage = "Block is bad due to some reason"; + + BadBlockException exception = new BadBlockException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertEquals(DEFAULT, exception.getType()); + } + + @Test + public void testBadBlockExceptionWithSpecificTypeAndMessage() { + String testMessage = "Failed to calculate Merkle root"; + + BadBlockException exception = new BadBlockException(CALC_MERKLE_ROOT_FAILED, testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertEquals(CALC_MERKLE_ROOT_FAILED, exception.getType()); + } + + @Test + public void testTypeEnumValues() { + assertEquals(Integer.valueOf(1), CALC_MERKLE_ROOT_FAILED.getValue()); + + assertEquals(Integer.valueOf(100), DEFAULT.getValue()); + } + + @Test + public void testBadItemExceptionDefaultConstructor() { + BadItemException exception = new BadItemException(); + assertNotNull(exception); + } + + @Test + public void testBadItemExceptionMessageConstructor() { + String expectedMessage = "This item is bad!"; + BadItemException exception = new BadItemException(expectedMessage); + assertEquals(expectedMessage, exception.getMessage()); + assertNull(exception.getCause()); + assertNotNull(exception); + } + + @Test + public void testBadItemExceptionMessageAndCauseConstructor() { + String expectedMessage = "This item is really bad!"; + Throwable expectedCause = new Throwable("Some underlying cause"); + BadItemException exception = new BadItemException(expectedMessage, expectedCause); + assertEquals(expectedMessage, exception.getMessage()); + assertEquals(expectedCause, exception.getCause()); + assertNotNull(exception); + } + + @Test + public void testBadNumberBlockExceptionDefaultConstructor() { + BadNumberBlockException exception = new BadNumberBlockException(); + assertNull(exception.getMessage()); + assertNotNull(exception); + } + + @Test + public void testBadNumberBlockExceptionMessageConstructor() { + String expectedMessage = "Number block is bad!"; + BadNumberBlockException exception = new BadNumberBlockException(expectedMessage); + assertEquals(expectedMessage, exception.getMessage()); + assertNotNull(exception); + } + + @Test + public void testBadTransactionExceptionDefaultConstructor() { + BadTransactionException exception = new BadTransactionException(); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + assertNotNull(exception); + } + + @Test + public void testBadTransactionExceptionMessageConstructor() { + String expectedMessage = "Transaction is bad!"; + BadTransactionException exception = new BadTransactionException(expectedMessage); + + assertEquals(expectedMessage, exception.getMessage()); + + assertNull(exception.getCause()); + + assertNotNull(exception); + } + + @Test + public void testBadTransactionExceptionMessageAndCauseConstructor() { + String expectedMessage = "Transaction failed due to an error"; + Throwable cause = new IllegalArgumentException("Invalid transaction data"); + + BadTransactionException exception = new BadTransactionException(expectedMessage, cause); + + assertEquals(expectedMessage, exception.getMessage()); + + assertEquals(cause, exception.getCause()); + + assertNotNull(exception); + } + + @Test + public void testBalanceInsufficientExceptionWithNoMessage() { + BalanceInsufficientException exception = new BalanceInsufficientException(); + assertNull(exception.getMessage()); + } + + @Test + public void testBalanceInsufficientExceptionWithMessage() { + String testMessage = "Balance is insufficient for this transaction"; + BalanceInsufficientException exception = new BalanceInsufficientException(testMessage); + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testCancelExceptionWithNoMessage() { + CancelException exception = new CancelException(); + + assertNull(exception.getMessage()); + } + + @Test + public void testCancelExceptionWithMessage() { + String testMessage = "Operation canceled by user"; + + CancelException exception = new CancelException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testCipherExceptionWithMessage() { + String testMessage = "Cipher operation failed"; + + CipherException exception = new CipherException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testCipherExceptionWithCause() { + Throwable testCause = new Throwable("Underlying error"); + + CipherException exception = new CipherException(testCause); + + assertSame(testCause, exception.getCause()); + + } + + @Test + public void testCipherExceptionWithMessageAndCause() { + String testMessage = "Cipher operation failed due to error"; + + Throwable testCause = new Throwable("Underlying error"); + CipherException exception = new CipherException(testMessage, testCause); + + assertEquals(testMessage, exception.getMessage()); + + assertSame(testCause, exception.getCause()); + } + + @Test + public void testContractExeExceptionWithNoMessage() { + ContractExeException exception = new ContractExeException(); + + assertNull(exception.getMessage()); + } + + @Test + public void testContractExeExceptionWithMessage() { + String testMessage = "Contract execution failed"; + + ContractExeException exception = new ContractExeException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testContractSizeNotEqualToOneExceptionWithNoMessage() { + ContractSizeNotEqualToOneException exception = new ContractSizeNotEqualToOneException(); + + assertNull(exception.getMessage()); + } + + @Test + public void testContractSizeNotEqualToOneExceptionWithMessage() { + String testMessage = "Contract size is not equal to one"; + + ContractSizeNotEqualToOneException exception = + new ContractSizeNotEqualToOneException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testContractValidateExceptionWithNoMessageOrThrowable() { + ContractValidateException exception = new ContractValidateException(); + + assertNull(exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testContractValidateExceptionWithMessage() { + String testMessage = "Contract validation failed"; + + ContractValidateException exception = new ContractValidateException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testContractValidateExceptionWithMessageAndThrowable() { + String testMessage = "Contract validation failed due to internal error"; + + Throwable cause = new RuntimeException("Internal error"); + + ContractValidateException exception = new ContractValidateException(testMessage, cause); + + assertEquals(testMessage, exception.getMessage()); + + assertSame(cause, exception.getCause()); + } + + @Test + public void testDupTransactionExceptionDefaultConstructor() { + DupTransactionException exception = new DupTransactionException(); + + assertNotNull(exception); + + } + + @Test + public void testDupTransactionExceptionMessageConstructor() { + String testMessage = "Duplicate Transaction Exception"; + DupTransactionException exception = new DupTransactionException(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testEventBloomExceptionDefaultConstructor() { + EventBloomException exception = new EventBloomException(); + + assertNotNull(exception); + + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testEventBloomExceptionMessageConstructor() { + String testMessage = "Event Bloom Exception occurred"; + EventBloomException exception = new EventBloomException(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testEventBloomExceptionMessageAndCauseConstructor() { + String testMessage = "Event Bloom Exception with cause"; + Throwable testCause = new Throwable("Root cause"); + EventBloomException exception = new EventBloomException(testMessage, testCause); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + + assertEquals(testCause, exception.getCause()); + } + + @Test + public void testHeaderNotFoundDefaultConstructor() { + HeaderNotFound exception = new HeaderNotFound(); + + assertNotNull(exception); + + assertNull(exception.getMessage()); + } + + @Test + public void testHeaderNotFoundMessageConstructor() { + String testMessage = "Header not found"; + HeaderNotFound exception = new HeaderNotFound(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testHighFreqExceptionDefaultConstructor() { + HighFreqException exception = new HighFreqException(); + + assertNotNull("Exception object should not be null", exception); + + assertNull("Exception message should be null", exception.getMessage()); + } + + @Test + public void testHighFreqExceptionMessageConstructor() { + String testMessage = "High frequency error occurred"; + HighFreqException exception = new HighFreqException(testMessage); + + assertNotNull("Exception object should not be null", exception); + + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + } + + @Test + public void testItemNotFoundExceptionWithMessage() { + String testMessage = "Item not found"; + ItemNotFoundException exception = new ItemNotFoundException(testMessage); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", testMessage, + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testItemNotFoundExceptionDefaultConstructor() { + ItemNotFoundException exception = new ItemNotFoundException(); + + assertNotNull("Exception object should not be null", exception); + assertNull("Exception message should be null when no message is provided", + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testItemNotFoundExceptionWithMessageAndCause() { + String testMessage = "Item not found in database"; + Throwable testCause = new Throwable("Database error"); + ItemNotFoundException exception = new ItemNotFoundException(testMessage, testCause); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + assertEquals("Cause should match the provided Throwable", testCause, exception.getCause()); + } + + @Test + public void testJsonRpcInternalExceptionDefaultConstructor() { + JsonRpcInternalException exception = new JsonRpcInternalException(); + + assertNotNull("Exception object should not be null", exception); + assertNull("Exception message should be null when no message is provided", + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInternalExceptionWithMessage() { + String testMessage = "Internal JSON-RPC error occurred"; + JsonRpcInternalException exception = new JsonRpcInternalException(testMessage); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", testMessage, + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInternalExceptionWithMessageAndCause() { + String testMessage = "Internal JSON-RPC processing failed"; + Throwable testCause = new Throwable("Underlying system error"); + JsonRpcInternalException exception = new JsonRpcInternalException(testMessage, testCause); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + assertEquals("Cause should match the provided Throwable", testCause, exception.getCause()); + } + + @Test + public void testJsonRpcInvalidParamsExceptionDefaultConstructor() { + JsonRpcInvalidParamsException exception = new JsonRpcInvalidParamsException(); + + assertNotNull("Exception object should not be null", exception); + assertNull("Exception message should be null when no message is provided", + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInvalidParamsExceptionWithMessage() { + String testMessage = "Invalid parameters provided"; + JsonRpcInvalidParamsException exception = new JsonRpcInvalidParamsException(testMessage); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInvalidParamsExceptionWithMessageAndCause() { + String testMessage = "Parameter validation failed"; + Throwable testCause = new Throwable("Underlying validation error"); + JsonRpcInvalidParamsException e = new JsonRpcInvalidParamsException(testMessage, testCause); + + assertNotNull("Exception object should not be null", e); + assertEquals("Exception message should match the provided message", testMessage, + e.getMessage()); + assertEquals("Cause should match the provided Throwable", testCause, e.getCause()); + } + + @Test + public void testJsonRpcInvalidRequestExceptionDefaultConstructor() { + JsonRpcInvalidRequestException exception = new JsonRpcInvalidRequestException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcInvalidRequestExceptionConstructorWithMessage() { + String testMessage = "Invalid JSON-RPC request"; + JsonRpcInvalidRequestException exception = new JsonRpcInvalidRequestException(testMessage); + assertNotNull(exception); + assertEquals(testMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcInvalidRequestExceptionConstructorWithMessageAndCause() { + String testMessage = "Invalid JSON-RPC request with cause"; + Throwable testCause = new Throwable("Root cause"); + JsonRpcInvalidRequestException e = new JsonRpcInvalidRequestException(testMessage, testCause); + assertNotNull(e); + assertEquals(testMessage, e.getMessage()); + assertEquals(testCause, e.getCause()); + } + + @Test + public void testJsonRpcMethodNotFoundExceptionDefaultConstructor() { + JsonRpcMethodNotFoundException exception = new JsonRpcMethodNotFoundException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcMethodNotFoundExceptionConstructorWithMessage() { + String testMessage = "JSON-RPC method not found"; + JsonRpcMethodNotFoundException exception = new JsonRpcMethodNotFoundException(testMessage); + assertNotNull(exception); + assertEquals(testMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcMethodNotFoundExceptionConstructorWithMessageAndCause() { + String testMessage = "JSON-RPC method not found with cause"; + Throwable testCause = new Throwable("Root cause"); + JsonRpcMethodNotFoundException e = new JsonRpcMethodNotFoundException(testMessage, testCause); + assertNotNull(e); + assertEquals(testMessage, e.getMessage()); + assertEquals(testCause, e.getCause()); + } + + @Test + public void testJsonRpcTooManyResultExceptionDefaultConstructor() { + JsonRpcTooManyResultException exception = new JsonRpcTooManyResultException(); + assertNotNull("Exception object should not be null", exception); + assertNull(exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testJsonRpcTooManyResultExceptionWithMessage() { + String testMessage = "Too many results returned by JSON-RPC method"; + JsonRpcTooManyResultException exception = new JsonRpcTooManyResultException(testMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testJsonRpcTooManyResultExceptionWithMessageAndCause() { + String testMessage = "Too many results returned with cause"; + Throwable testCause = new Throwable("Root cause"); + JsonRpcTooManyResultException e = new JsonRpcTooManyResultException(testMessage, testCause); + assertNotNull("Exception object should not be null", e); + assertEquals("Message should match the provided message", testMessage, e.getMessage()); + assertEquals("Cause should match the provided cause", testCause, e.getCause()); + } + + @Test + public void testNonCommonBlockExceptionDefaultConstructor() { + NonCommonBlockException exception = new NonCommonBlockException(); + assertNotNull("Exception object should not be null", exception); + assertNull("Message should be null for default constructor", exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testNonCommonBlockExceptionWithMessage() { + String testMessage = "Block is not common"; + NonCommonBlockException exception = new NonCommonBlockException(testMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testNonCommonBlockExceptionWithMessageAndCause() { + String testMessage = "Block is not common due to some error"; + Throwable testCause = new Throwable("Root cause of the error"); + NonCommonBlockException exception = new NonCommonBlockException(testMessage, testCause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertEquals("Cause should match the provided cause", testCause, exception.getCause()); + } + + @Test + public void testDefaultConstructor() { + NonUniqueObjectException exception = new NonUniqueObjectException(); + assertNotNull("Exception object should not be null", exception); + assertNull("Message should be null for default constructor", exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testConstructorWithMessage() { + String testMessage = "Object is not unique"; + NonUniqueObjectException exception = new NonUniqueObjectException(testMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testConstructorWithMessageAndCause() { + String testMessage = "Object is not unique due to a conflict"; + Throwable testCause = new Throwable("Conflict error"); + NonUniqueObjectException exception = new NonUniqueObjectException(testMessage, testCause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertEquals("Cause should match the provided cause", testCause, exception.getCause()); + } + + @Test + public void testConstructorWithCauseOnly() { + Throwable testCause = new Throwable("Root cause of non-uniqueness"); + NonUniqueObjectException exception = new NonUniqueObjectException(testCause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should be empty string when only cause is provided", "", + exception.getMessage()); + assertEquals("Cause should match the provided cause", testCause, exception.getCause()); + } + + @Test + public void testConstructorWithTypeEnumAndErrMsg() { + P2pException exception = new P2pException(NO_SUCH_MESSAGE, "Test error message"); + assertNotNull("Exception should not be null", exception); + assertEquals("Error message should match", "Test error message", exception.getMessage()); + assertEquals("Exception type should be NO_SUCH_MESSAGE", NO_SUCH_MESSAGE, exception.getType()); + } + + @Test + public void testConstructorWithTypeEnumAndThrowable() { + Throwable cause = new Throwable("Cause of the error"); + P2pException exception = new P2pException(PARSE_MESSAGE_FAILED, cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Cause should match", cause, exception.getCause()); + } + + @Test + public void testConstructorWithTypeEnumErrMsgAndThrowable() { + Throwable cause = new Throwable("Cause of the error"); + P2pException exception = new P2pException(SYNC_FAILED, "Test error message", cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Error message should match", + "Test error message", exception.getMessage()); + assertEquals("Cause should match", cause, exception.getCause()); + assertEquals("Exception type should be SYNC_FAILED", SYNC_FAILED, exception.getType()); + } + + @Test + public void testP2pExceptionTypeEnumValues() { + assertNotNull(NO_SUCH_MESSAGE.toString()); + assertEquals("NO_SUCH_MESSAGE value should be 1", + Integer.valueOf(1), NO_SUCH_MESSAGE.getValue()); + assertEquals("NO_SUCH_MESSAGE desc should be 'no such message'", + "no such message", NO_SUCH_MESSAGE.getDesc()); + + assertEquals("DEFAULT value should be 100", Integer.valueOf(100), + P2pException.TypeEnum.DEFAULT.getValue()); + assertEquals("DEFAULT desc should be 'default exception'", + "default exception", P2pException.TypeEnum.DEFAULT.getDesc()); + } + + @Test + public void testPermissionExceptionDefaultConstructor() { + PermissionException exception = new PermissionException(); + assertNotNull(exception); + } + + @Test + public void testPermissionExceptionWithMessage() { + String errorMessage = "You do not have sufficient permissions to perform this operation"; + PermissionException exception = new PermissionException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testReceiptCheckErrExceptionDefaultConstructor() { + ReceiptCheckErrException exception = new ReceiptCheckErrException(); + assertNotNull("Exception object should not be null", exception); + assertNull("Message should be null for default constructor", exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testReceiptCheckErrExceptionConstructorWithMessage() { + String errorMessage = "Receipt check failed due to invalid data"; + ReceiptCheckErrException exception = new ReceiptCheckErrException(errorMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the input message", errorMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testReceiptCheckErrExceptionConstructorWithMessageAndCause() { + String errorMessage = "Receipt check error"; + Throwable cause = new Throwable("Underlying database error"); + ReceiptCheckErrException exception = new ReceiptCheckErrException(errorMessage, cause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the input message", errorMessage, exception.getMessage()); + assertEquals("Cause should match the input cause", cause, exception.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionDefaultConstructor() { + RevokingStoreIllegalStateException exception = new RevokingStoreIllegalStateException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithMessage() { + String errorMessage = "Invalid state for revoking store"; + RevokingStoreIllegalStateException e = new RevokingStoreIllegalStateException(errorMessage); + assertNotNull("Exception should not be null", e); + assertEquals("Message should match the input message", errorMessage, e.getMessage()); + assertNull("Cause should be null", e.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithMessageAndCause() { + String errorMessage = "Error occurred during revocation"; + Throwable cause = new Throwable("Database connection failed"); + RevokingStoreIllegalStateException e = + new RevokingStoreIllegalStateException(errorMessage, cause); + assertNotNull("Exception should not be null", e); + assertEquals("Message should match the input message", errorMessage, e.getMessage()); + assertEquals("Cause should match the input cause", cause, e.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithCauseOnly() { + Throwable cause = new Throwable("Unknown error"); + RevokingStoreIllegalStateException exception = new RevokingStoreIllegalStateException(cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should be empty string", "", exception.getMessage()); + assertEquals("Cause should match the input cause", cause, exception.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithActiveSession() { + int activeSession = 0; + RevokingStoreIllegalStateException e = new RevokingStoreIllegalStateException(activeSession); + assertNotNull("Exception should not be null", e); + assertEquals("Message should indicate activeSession is not greater than 0", + "activeSession 0 has to be greater than 0", e.getMessage()); + } + + @Test + public void testSignatureFormatExceptionDefaultConstructor() { + SignatureFormatException exception = new SignatureFormatException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + } + + @Test + public void testSignatureFormatExceptionWithMessage() { + String errorMessage = "Invalid signature format"; + SignatureFormatException exception = new SignatureFormatException(errorMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match the provided error message", + errorMessage, exception.getMessage()); + } + + @Test + public void testStoreExceptionDefaultConstructor() { + StoreException exception = new StoreException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testStoreExceptionWithMessage() { + String errorMessage = "Store error occurred"; + StoreException exception = new StoreException(errorMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match the provided error message", + errorMessage, exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testStoreExceptionWithMessageAndCause() { + String errorMessage = "Store error occurred"; + Throwable cause = new Throwable("Root cause"); + StoreException exception = new StoreException(errorMessage, cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match the provided error message", + errorMessage, exception.getMessage()); + assertEquals("Cause should match the provided cause", cause, exception.getCause()); + } + + @Test + public void testStoreExceptionWithCause() { + Throwable cause = new Throwable("Root cause"); + StoreException exception = new StoreException(cause); + assertNotNull("Exception should not be null", exception); + } + + + @Test + public void testTaposExceptionDefaultConstructor() { + TaposException exception = new TaposException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTaposExceptionWithMessage() { + String errorMessage = "Tapos error occurred"; + TaposException exception = new TaposException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTaposExceptionWithMessageAndCause() { + String errorMessage = "Tapos error occurred"; + Throwable cause = new Throwable("Root cause"); + TaposException exception = new TaposException(errorMessage, cause); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTooBigTransactionExceptionDefaultConstructor() { + TooBigTransactionException exception = new TooBigTransactionException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + } + + @Test + public void testTooBigTransactionExceptionWithMessage() { + String errorMessage = "Transaction is too big"; + TooBigTransactionException exception = new TooBigTransactionException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testTooBigTransactionResultExceptionDefaultConstructor() { + TooBigTransactionResultException exception = new TooBigTransactionResultException(); + assertNotNull(exception); + assertEquals("too big transaction result", + exception.getMessage()); + } + + @Test + public void testTooBigTransactionResultExceptionWithMessage() { + String customMessage = "Custom error message for too big transaction result"; + TooBigTransactionResultException e = new TooBigTransactionResultException(customMessage); + assertNotNull(e); + assertEquals(customMessage, e.getMessage()); + } + + @Test + public void testTraitorPeerExceptionDefaultConstructor() { + TraitorPeerException exception = new TraitorPeerException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTraitorPeerExceptionWithMessage() { + String errorMessage = "Peer is a traitor"; + TraitorPeerException exception = new TraitorPeerException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTraitorPeerExceptionWithMessageAndCause() { + String errorMessage = "Peer is a traitor and caused an error"; + Throwable cause = new Throwable("Underlying cause"); + TraitorPeerException exception = new TraitorPeerException(errorMessage, cause); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTransactionExpirationExceptionDefaultConstructor() { + TransactionExpirationException exception = new TransactionExpirationException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + } + + @Test + public void testTransactionExpirationExceptionWithMessage() { + String errorMessage = "Transaction has expired"; + TransactionExpirationException exception = new TransactionExpirationException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testTronRuntimeExceptionDefaultConstructor() { + TronRuntimeException exception = new TronRuntimeException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTronRuntimeExceptionWithMessage() { + String errorMessage = "An error occurred"; + TronRuntimeException exception = new TronRuntimeException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTronRuntimeExceptionWithMessageAndCause() { + String errorMessage = "An error occurred due to a cause"; + Throwable cause = new Throwable("Underlying cause"); + TronRuntimeException exception = new TronRuntimeException(errorMessage, cause); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTronRuntimeExceptionWithCause() { + Throwable cause = new Throwable("Underlying cause without message"); + TronRuntimeException exception = new TronRuntimeException(cause); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTypeMismatchNamingException_WithRequiredAndActualTypes() { + try { + throw new TypeMismatchNamingException("someName", String.class, Integer.class); + } catch (TypeMismatchNamingException e) { + assertEquals("Object of type [class java.lang.Integer] available at store location " + + "[someName] is not assignable to [java.lang.String]", e.getMessage()); + assertEquals(String.class, e.getRequiredType()); + assertEquals(Integer.class, e.getActualType()); + } + } + + @Test + public void testTypeMismatchNamingException_WithExplanation() { + try { + throw new TypeMismatchNamingException("Custom explanation"); + } catch (TypeMismatchNamingException e) { + assertEquals("Custom explanation", e.getMessage()); + assertNull(e.getRequiredType()); + assertNull(e.getActualType()); + } + } + + @Test + public void testUnLinkedBlockExceptionDefaultConstructor() { + UnLinkedBlockException exception = new UnLinkedBlockException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testUnLinkedBlockExceptionWithMessage() { + String testMessage = "This block is not linked"; + UnLinkedBlockException exception = new UnLinkedBlockException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testUnLinkedBlockExceptionWithMessageAndCause() { + String testMessage = "This block is not linked due to an error"; + Throwable testCause = new Throwable("Cause of the error"); + UnLinkedBlockException exception = new UnLinkedBlockException(testMessage, testCause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertEquals("Cause should match", testCause, exception.getCause()); + } + + @Test + public void testUnReachBlockExceptionDefaultConstructor() { + UnReachBlockException exception = new UnReachBlockException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testUnReachBlockExceptionWithMessage() { + String testMessage = "Block is unreachable"; + UnReachBlockException exception = new UnReachBlockException(testMessage); + assertNotNull(exception); + assertEquals(testMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testUnReachBlockExceptionWithMessageAndCause() { + String testMessage = "Block is unreachable due to an error"; + Throwable testCause = new Throwable("Cause of the error"); + UnReachBlockException exception = new UnReachBlockException(testMessage, testCause); + assertNotNull(exception); + assertEquals(testCause, exception.getCause()); + } + + @Test + public void testValidateScheduleExceptionDefaultConstructor() { + ValidateScheduleException exception = new ValidateScheduleException(); + + assertNotNull(exception); + + assertNull(exception.getMessage()); + } + + @Test + public void testValidateScheduleExceptionConstructorWithMessage() { + String testMessage = "Schedule validation failed"; + + ValidateScheduleException exception = new ValidateScheduleException(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testValidateSignatureExceptionDefaultConstructor() { + ValidateSignatureException exception = new ValidateSignatureException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + } + + @Test + public void testValidateSignatureExceptionConstructorWithMessage() { + String testMessage = "Signature validation failed"; + ValidateSignatureException exception = new ValidateSignatureException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + } + + @Test + public void testVMIllegalExceptionDefaultConstructor() { + VMIllegalException exception = new VMIllegalException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + } + + @Test + public void testVMIllegalExceptionConstructorWithMessage() { + String testMessage = "VM operation is illegal"; + VMIllegalException exception = new VMIllegalException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + } + + @Test + public void testZkProofValidateExceptionWithFirstValidatedTrue() { + String testMessage = "Zero-knowledge proof validation failed, but first part was validated"; + boolean firstValidated = true; + + ZkProofValidateException exception = new ZkProofValidateException(testMessage, firstValidated); + + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertTrue("firstValidated should be true", exception.isFirstValidated()); + } + + @Test + public void testZkProofValidateExceptionWithFirstValidatedFalse() { + String testMessage = "Zero-knowledge proof validation failed, first part not validated"; + boolean firstValidated = false; + + ZkProofValidateException exception = new ZkProofValidateException(testMessage, firstValidated); + exception.setFirstValidated(true); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertTrue("firstValidated should be true", exception.isFirstValidated()); + } + + @Test + public void testZksnarkExceptionNoMessage() { + ZksnarkException exception = new ZksnarkException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + } + + @Test + public void testZksnarkExceptionWithMessage() { + String testMessage = "Zksnark validation failed"; + ZksnarkException exception = new ZksnarkException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + } + + @Test + public void testTronDBExceptionNoArgs() { + TronDBException exception = new TronDBException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testTronDBExceptionWithMessage() { + String testMessage = "Database error occurred"; + TronDBException exception = new TronDBException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testTronDBExceptionWithMessageAndThrowable() { + String testMessage = "Database error with specific cause"; + Throwable testCause = new Throwable("Root cause"); + TronDBException exception = new TronDBException(testMessage, testCause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertEquals("Cause should match", testCause, exception.getCause()); + } + + @Test + public void testTronDBExceptionWithThrowable() { + Throwable testCause = new Throwable("Root cause without message"); + TronDBException exception = new TronDBException(testCause); + assertNotNull("Exception should not be null", exception); + assertEquals("Cause should match", testCause, exception.getCause()); + } +} 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 cba4a7d8040..500e7454dbe 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 @@ -14,12 +14,16 @@ public class RLPListTest { @Test public void testRecursivePrint() { RLPItem element = new RLPItem("rlpItem".getBytes()); - Assert.assertEquals(new String(element.getRLPData()), "rlpItem"); + Assert.assertEquals("rlpItem", new String(element.getRLPData())); RLPList.recursivePrint(element); RLPList rlpList = new RLPList(); rlpList.add(new RLPItem("rlpItem0".getBytes())); RLPList.recursivePrint(rlpList); Assert.assertThrows(RuntimeException.class, () -> RLPList.recursivePrint(null)); + + RLPItem rlpItem = new RLPItem(new byte[0]); + Assert.assertNull(rlpItem.getRLPData()); + } @Test diff --git a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java index d0222254c7d..27d5effd6b1 100644 --- a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java +++ b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java @@ -24,8 +24,8 @@ public class LocalWitnessTest { - private LocalWitnesses localWitness = new LocalWitnesses(); - private static String PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); + private final LocalWitnesses localWitness = new LocalWitnesses(); + private static final String PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); @Before public void setLocalWitness() { @@ -38,11 +38,15 @@ public void setLocalWitness() { @Test public void whenSetNullPrivateKey() { localWitness.setPrivateKeys(null); + Assert.assertNotNull(localWitness.getPrivateKey()); + Assert.assertNotNull(localWitness.getPublicKey()); } @Test public void whenSetEmptyPrivateKey() { localWitness.setPrivateKeys(Lists.newArrayList("")); + Assert.assertNotNull(localWitness.getPrivateKey()); + Assert.assertNotNull(localWitness.getPublicKey()); } @Test(expected = IllegalArgumentException.class) @@ -58,6 +62,7 @@ public void whenSetPrefixPrivateKey() { localWitness .setPrivateKeys(Lists .newArrayList("0X" + PRIVATE_KEY)); + Assert.assertNotNull(localWitness.getPrivateKey()); } @Test @@ -66,4 +71,20 @@ public void getPrivateKey() { .newArrayList(PRIVATE_KEY), localWitness.getPrivateKeys()); } + + @Test + public void testConstructor() { + LocalWitnesses localWitnesses = new LocalWitnesses(PublicMethod.getRandomPrivateKey()); + LocalWitnesses localWitnesses1 = + new LocalWitnesses(Lists.newArrayList(PublicMethod.getRandomPrivateKey())); + localWitnesses.setWitnessAccountAddress(new byte[0]); + Assert.assertNotNull(localWitnesses1.getPublicKey()); + + LocalWitnesses localWitnesses2 = new LocalWitnesses(); + Assert.assertNull(localWitnesses2.getPrivateKey()); + Assert.assertNull(localWitnesses2.getPublicKey()); + localWitnesses2.initWitnessAccountAddress(true); + LocalWitnesses localWitnesses3 = new LocalWitnesses(); + Assert.assertNotNull(localWitnesses3.getWitnessAccountAddress(true)); + } } 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 ddf741fb6fa..07440435f41 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -367,12 +367,12 @@ public void entityTest() { Assert.assertTrue(trie.isEmpty()); AccountStateEntity entity = new AccountStateEntity(); AccountStateEntity parsedEntity = AccountStateEntity.parse("".getBytes()); - Assert.assertTrue(parsedEntity != null); - Assert.assertTrue(parsedEntity.getAccount() != null); - Assert.assertTrue(org.tron.core.db.api.pojo.Account.of() != null); - Assert.assertTrue(org.tron.core.db.api.pojo.AssetIssue.of() != null); - Assert.assertTrue(org.tron.core.db.api.pojo.Block.of() != null); - Assert.assertTrue(org.tron.core.db.api.pojo.Transaction.of() != null); + Assert.assertNotNull(parsedEntity); + Assert.assertNotNull(parsedEntity.getAccount()); + Assert.assertNotNull(org.tron.core.db.api.pojo.Account.of()); + Assert.assertNotNull(org.tron.core.db.api.pojo.AssetIssue.of()); + Assert.assertNotNull(org.tron.core.db.api.pojo.Block.of()); + Assert.assertNotNull(org.tron.core.db.api.pojo.Transaction.of()); } diff --git a/framework/src/test/java/org/tron/core/db/api/pojo/PojoTest.java b/framework/src/test/java/org/tron/core/db/api/pojo/PojoTest.java new file mode 100644 index 00000000000..f4661725a02 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/api/pojo/PojoTest.java @@ -0,0 +1,80 @@ +package org.tron.core.db.api.pojo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Lists; +import org.junit.Test; + +public class PojoTest { + + @Test + public void testAccountCreation() { + Account account = Account.of(); + account.setName("testName"); + account.setAddress("testAddress"); + account.setBalance(1622548800000L); + + assertNotNull(account); + assertEquals("testName", account.getName()); + assertEquals("testAddress", account.getAddress()); + assertEquals(1622548800000L, account.getBalance()); + } + + @Test + public void testAssetIssueCreation() { + AssetIssue assetIssue = AssetIssue.of(); + assetIssue.setName("testName"); + assetIssue.setAddress("testAddress"); + assetIssue.setStart(1622548800000L); + assetIssue.setEnd(1654084800000L); + + assertNotNull(assetIssue); + assertEquals("testName", assetIssue.getName()); + assertEquals("testAddress", assetIssue.getAddress()); + assertEquals(1622548800000L, assetIssue.getStart()); + assertEquals(1654084800000L, assetIssue.getEnd()); + } + + @Test + public void testBlockCreation() { + Block block = Block.of(); + block.setId("7654321"); + block.setNumber(1000L); + block.setTransactionIds(Lists.newArrayList("1234567")); + + assertNotNull(block); + assertEquals("7654321", block.getId()); + assertEquals(1000L, block.getNumber()); + assertEquals("1234567", block.getTransactionIds().get(0)); + } + + @Test + public void testTransactionCreation() { + Transaction transaction = Transaction.of(); + transaction.setId("7654321"); + transaction.setFrom("from"); + transaction.setTo("to"); + + assertNotNull(transaction); + assertEquals("7654321", transaction.getId()); + assertEquals("from", transaction.getFrom()); + assertEquals("to", transaction.getTo()); + } + + @Test + public void testWitnessCreation() { + Witness witness = Witness.of(); + witness.setAddress("testAddress"); + witness.setJobs(true); + witness.setUrl("https://cryptoai.com"); + witness.setPublicKey("wergfsioejgbrotjsdfdoqwj"); + + assertNotNull(witness); + assertEquals("testAddress", witness.getAddress()); + assertTrue(witness.isJobs()); + assertEquals("https://cryptoai.com", witness.getUrl()); + assertEquals("wergfsioejgbrotjsdfdoqwj", witness.getPublicKey()); + } +} diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java index 95cb9d0597f..dab76cfcb46 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java @@ -9,6 +9,7 @@ import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.config.Parameter.NetConstants; import org.tron.core.exception.P2pException; +import org.tron.core.net.message.keepalive.PingMessage; import org.tron.core.net.message.sync.ChainInventoryMessage; import org.tron.core.net.peer.PeerConnection; @@ -20,11 +21,11 @@ public class ChainInventoryMsgHandlerTest { private List blockIds = new ArrayList<>(); @Test - public void testProcessMessage() { + public void testProcessMessage() throws Exception { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("not send syncBlockChainMsg")); + Assert.assertEquals("not send syncBlockChainMsg", e.getMessage()); } peer.setSyncChainRequested(new Pair<>(new LinkedList<>(), System.currentTimeMillis())); @@ -32,7 +33,7 @@ public void testProcessMessage() { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("blockIds is empty")); + Assert.assertEquals("blockIds is empty", e.getMessage()); } long size = NetConstants.SYNC_FETCH_BATCH_NUM + 2; @@ -44,7 +45,7 @@ public void testProcessMessage() { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("big blockIds size: " + size)); + Assert.assertEquals(e.getMessage(), "big blockIds size: " + size); } blockIds.clear(); @@ -57,8 +58,10 @@ public void testProcessMessage() { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("remain: 100, blockIds size: " + size)); + Assert.assertEquals(e.getMessage(), "remain: 100, blockIds size: " + size); } + Assert.assertNotNull(msg.toString()); + Assert.assertNull(msg.getAnswerMessage()); } } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java index d4ad32dd34f..e654e1c9cc2 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java @@ -19,6 +19,7 @@ import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; +import org.tron.core.net.message.sync.BlockInventoryMessage; import org.tron.core.net.message.sync.SyncBlockChainMessage; import org.tron.core.net.peer.PeerConnection; import org.tron.p2p.connection.Channel; @@ -56,7 +57,7 @@ public void testProcessMessage() throws Exception { try { handler.processMessage(peer, new SyncBlockChainMessage(new ArrayList<>())); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("SyncBlockChain blockIds is empty")); + Assert.assertEquals("SyncBlockChain blockIds is empty", e.getMessage()); } List blockIds = new ArrayList<>(); @@ -66,7 +67,10 @@ public void testProcessMessage() throws Exception { "check", PeerConnection.class, SyncBlockChainMessage.class); method.setAccessible(true); boolean f = (boolean)method.invoke(handler, peer, message); - Assert.assertTrue(!f); + Assert.assertNotNull(message.getAnswerMessage()); + Assert.assertNotNull(message.toString()); + Assert.assertNotNull(((BlockInventoryMessage) message).getAnswerMessage()); + Assert.assertFalse(f); Method method1 = handler.getClass().getDeclaredMethod( "getLostBlockIds", List.class, BlockId.class); @@ -80,7 +84,7 @@ public void testProcessMessage() throws Exception { Method method2 = handler.getClass().getDeclaredMethod( "getBlockIds", Long.class, BlockId.class); method2.setAccessible(true); - List list = (List) method2.invoke(handler, 0L, new BlockCapsule.BlockId()); + List list = (List) method2.invoke(handler, 0L, new BlockCapsule.BlockId()); Assert.assertEquals(1, list.size()); } diff --git a/framework/src/test/java/org/tron/core/net/service/nodepersist/DBNodeTest.java b/framework/src/test/java/org/tron/core/net/service/nodepersist/DBNodeTest.java new file mode 100644 index 00000000000..171701762ee --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/service/nodepersist/DBNodeTest.java @@ -0,0 +1,52 @@ +package org.tron.core.net.service.nodepersist; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.beust.jcommander.internal.Lists; +import org.junit.Before; +import org.junit.Test; + +public class DBNodeTest { + private DBNode dbNode1; + private DBNode dbNode2; + + @Before + public void setUp() { + dbNode1 = new DBNode("localhost", 3306); + dbNode2 = new DBNode(); + } + + @Test + public void testConstructorWithParameters() { + assertEquals("localhost", dbNode1.getHost()); + assertEquals(3306, dbNode1.getPort()); + } + + @Test + public void testDefaultConstructor() { + assertNull(dbNode2.getHost()); + assertEquals(0, dbNode2.getPort()); + } + + @Test + public void testSetAndGetHost() { + dbNode2.setHost("127.0.0.1"); + assertEquals("127.0.0.1", dbNode2.getHost()); + } + + @Test + public void testSetAndGetPort() { + dbNode2.setPort(5432); + assertEquals(5432, dbNode2.getPort()); + } + + + @Test + public void testDBNodes() { + DBNodes dbNodes = new DBNodes(); + dbNodes.setNodes(Lists.newArrayList(dbNode1, dbNode2)); + assertEquals(3306, dbNodes.getNodes().get(0).getPort()); + assertEquals(0, dbNodes.getNodes().get(1).getPort()); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java index 4a844c49c3c..7746066abfa 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java @@ -1695,6 +1695,7 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println( "rk:" + ByteArray.toHexString(spendDescriptionCapsule.getRk().toByteArray())); spendDescriptionCapsule.setRk(fakeRk); + spendDescriptionCapsule.setRk(ByteString.copyFrom(fakeRk)); return spendDescriptionCapsule; } }; @@ -1737,6 +1738,9 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo .toHexString(spendDescriptionCapsule.getZkproof().toByteArray())); spendDescriptionCapsule.setZkproof(fakeProof); + spendDescriptionCapsule.setZkproof(ByteString.copyFrom(fakeProof)); + spendDescriptionCapsule.setSpendAuthoritySignature(spendDescriptionCapsule + .getSpendAuthoritySignature()); return spendDescriptionCapsule; } }; @@ -1775,6 +1779,7 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println( "nf:" + ByteArray.toHexString(spendDescriptionCapsule.getNullifier().toByteArray())); spendDescriptionCapsule.setNullifier(bytes); + spendDescriptionCapsule.setNullifier(ByteString.copyFrom(bytes)); return spendDescriptionCapsule; } }; @@ -1811,6 +1816,9 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println( "bytes:" + ByteArray.toHexString(spendDescriptionCapsule.getAnchor().toByteArray())); spendDescriptionCapsule.setAnchor(bytes); + spendDescriptionCapsule.setAnchor(ByteString.copyFrom(bytes)); + spendDescriptionCapsule.setValueCommitment(new byte[32]); + spendDescriptionCapsule.setValueCommitment(ByteString.copyFrom(new byte[32])); return spendDescriptionCapsule; } }; @@ -1827,5 +1835,14 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println("Done"); } } + + SpendDescriptionCapsule c = new SpendDescriptionCapsule(new byte[32]); + SpendDescriptionCapsule c1 = new SpendDescriptionCapsule(ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]),ByteString.copyFrom(new byte[32])); + Assert.assertNotNull(c); + Assert.assertNotNull(c1); } } diff --git a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java index f3ad1f36cd1..157a7ba732f 100755 --- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java @@ -369,6 +369,8 @@ public String[] generateSpendAndOutputParams() throws ZksnarkException, BadItemE // generate checkSpendParams SpendDescription spendDescription = builder.getContractBuilder().getSpendDescription(0); + SpendDescriptionCapsule spendDescriptionCapsule = new SpendDescriptionCapsule(spendDescription); + Assert.assertNotNull(spendDescriptionCapsule); CheckSpendParams checkSpendParams = new CheckSpendParams(ctx, spendDescription.getValueCommitment().toByteArray(), spendDescription.getAnchor().toByteArray(), @@ -873,20 +875,43 @@ private ReceiveDescriptionCapsule changeGenerateOutputProof(ReceiveDescriptionIn JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); throw new ZksnarkException("Output proof failed"); } - + ReceiveDescriptionCapsule c = new ReceiveDescriptionCapsule(new byte[32]); + ReceiveDescriptionCapsule c1 = + new ReceiveDescriptionCapsule(ReceiveDescription.newBuilder().build()); + ReceiveDescriptionCapsule c2 = + new ReceiveDescriptionCapsule(ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32])); + Assert.assertNotNull(c); + Assert.assertNotNull(c1); + Assert.assertNotNull(c2); ReceiveDescriptionCapsule receiveDescriptionCapsule = new ReceiveDescriptionCapsule(); receiveDescriptionCapsule.setValueCommitment(cv); + receiveDescriptionCapsule.setValueCommitment(ByteString.copyFrom(cv)); receiveDescriptionCapsule.setNoteCommitment(cm); + receiveDescriptionCapsule.setNoteCommitment(ByteString.copyFrom(cm)); receiveDescriptionCapsule.setEpk(encryptor.getEpk()); + receiveDescriptionCapsule.setEpk(ByteString.copyFrom(encryptor.getEpk())); receiveDescriptionCapsule.setCEnc(enc.getEncCiphertext()); + receiveDescriptionCapsule.setCEnc(ByteString.copyFrom(enc.getEncCiphertext())); receiveDescriptionCapsule.setZkproof(zkProof); + receiveDescriptionCapsule.setZkproof(ByteString.copyFrom(zkProof)); + receiveDescriptionCapsule.getEphemeralKey(); + receiveDescriptionCapsule.getData(); + receiveDescriptionCapsule.getZkproof(); + receiveDescriptionCapsule.getOutCiphertext(); OutgoingPlaintext outPlaintext = new OutgoingPlaintext(output.getNote().getPkD(), encryptor.getEsk()); - receiveDescriptionCapsule.setCOut(outPlaintext + byte[] bytes = outPlaintext .encrypt(output.getOvk(), receiveDescriptionCapsule.getValueCommitment().toByteArray(), receiveDescriptionCapsule.getCm().toByteArray(), - encryptor).getData()); + encryptor).getData(); + receiveDescriptionCapsule.setCOut(bytes); + receiveDescriptionCapsule.setCOut(ByteString.copyFrom(bytes)); Note newNote = output.getNote(); byte[] newCm; diff --git a/framework/src/test/java/org/tron/program/SupplementTest.java b/framework/src/test/java/org/tron/program/SupplementTest.java index ffa6b14f46b..3dfa23dfce4 100644 --- a/framework/src/test/java/org/tron/program/SupplementTest.java +++ b/framework/src/test/java/org/tron/program/SupplementTest.java @@ -1,8 +1,10 @@ package org.tron.program; +import static org.apache.commons.lang3.StringUtils.EMPTY; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.tron.keystore.WalletUtils.passwordValid; import java.io.File; import java.io.IOException; @@ -21,6 +23,7 @@ import org.tron.core.Constant; import org.tron.core.capsule.StorageRowCapsule; import org.tron.core.capsule.utils.RLP; +import org.tron.core.config.TronLogShutdownHook; import org.tron.core.config.args.Args; import org.tron.core.services.http.HttpSelfFormatFieldName; import org.tron.core.store.StorageRowStore; @@ -130,4 +133,18 @@ public void testGet() throws Exception { RLP.unwrapList(new byte[] {1,2,3,4,5,6,7}); } + @Test + public void testPasswordValid() { + assertFalse(passwordValid(EMPTY)); + assertFalse(passwordValid("12345")); + assertTrue(passwordValid("123456")); + } + + @Test + public void testRun() { + TronLogShutdownHook hook = new TronLogShutdownHook(); + hook.run(); + assertTrue(true); + } + }