From fe065dac0672311a40df0d71f1de526c582dd5bc Mon Sep 17 00:00:00 2001 From: chaozhu Date: Thu, 14 Nov 2024 17:56:01 +0800 Subject: [PATCH 1/4] update jacoco version --- plugins/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/build.gradle b/plugins/build.gradle index b85a435dc30..7028686f3d0 100644 --- a/plugins/build.gradle +++ b/plugins/build.gradle @@ -6,7 +6,7 @@ apply plugin: 'application' apply plugin: 'checkstyle' jacoco { - toolVersion = "0.8.4" + toolVersion = "0.8.8" } def versions = [ checkstyle: '8.7', From 704720187336e69d2b9d3dbf14128fe46532bee8 Mon Sep 17 00:00:00 2001 From: chaozhu Date: Mon, 9 Dec 2024 20:14:59 +0800 Subject: [PATCH 2/4] upgrade mockito and optimize tests coverage --- build.gradle | 3 +- .../TransactionLogTriggerCapsuleMockTest.java | 127 ++ .../TransactionLogTriggerCapsuleTest.java | 69 + .../common/runtime/RuntimeImplMockTest.java | 54 + .../java/org/tron/core/WalletMockTest.java | 1330 +++++++++++++++++ .../org/tron/core/db/ManagerMockTest.java | 447 ++++++ .../net/peer/PeerStatusCheckMockTest.java | 28 + .../core/services/http/JsonFormatTest.java | 255 ++++ .../tron/core/services/http/UtilMockTest.java | 243 +++ 9 files changed, 2555 insertions(+), 1 deletion(-) create mode 100644 framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java create mode 100644 framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java create mode 100644 framework/src/test/java/org/tron/core/WalletMockTest.java create mode 100644 framework/src/test/java/org/tron/core/db/ManagerMockTest.java create mode 100644 framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java create mode 100644 framework/src/test/java/org/tron/core/services/http/UtilMockTest.java diff --git a/build.gradle b/build.gradle index b1aba1c0aa9..c74a31a3c8e 100644 --- a/build.gradle +++ b/build.gradle @@ -52,7 +52,8 @@ subprojects { testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' testImplementation group: 'junit', name: 'junit', version: '4.13.2' - testImplementation "org.mockito:mockito-core:2.13.0" + testImplementation "org.mockito:mockito-core:4.11.0" + testImplementation "org.mockito:mockito-inline:4.11.0" } task sourcesJar(type: Jar, dependsOn: classes) { diff --git a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java new file mode 100644 index 00000000000..65c485b22d9 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java @@ -0,0 +1,127 @@ +package org.tron.common.logsfilter; + + +import com.google.protobuf.ByteString; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; +import org.tron.common.logsfilter.trigger.InternalTransactionPojo; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.ProgramResult; +import org.tron.common.runtime.RuntimeImpl; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.ReceiptCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.db.TransactionTrace; +import org.tron.p2p.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + + +public class TransactionLogTriggerCapsuleMockTest { + + private static final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + private static final String RECEIVER_ADDRESS = "41abd4b9367799eaa3197fecb144eb71de1e049150"; + private static final String CONTRACT_ADDRESS = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; + + private TransactionCapsule transactionCapsule; + private BlockCapsule blockCapsule; + + @Before + public void setup() { + blockCapsule = new BlockCapsule(1, + Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), + Sha256Hash.ZERO_HASH.getByteString() + ); + } + + @After + public void clearMocks() { + + } + + + @Test + public void testConstructorWithTransactionTrace() { + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = spy(new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract)); + + TransactionTrace trace = mock(TransactionTrace.class); + ReceiptCapsule receiptCapsule = new ReceiptCapsule(Sha256Hash.ZERO_HASH); + RuntimeImpl runtime = mock(RuntimeImpl.class); + List logs = new ArrayList<>(); + logs.add(Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom("address".getBytes())) + .setData(ByteString.copyFrom("data".getBytes())) + .addTopics(ByteString.copyFrom("topic".getBytes())) + .build()); + + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder() + .addAllLog(logs); + + ProgramResult programResult = ProgramResult.createEmpty(); + programResult.setHReturn("hreturn".getBytes()); + programResult.setContractAddress(CONTRACT_ADDRESS.getBytes()); + + when(transactionCapsule.getTrxTrace()).thenReturn(trace); + when(trace.getReceipt()).thenReturn(receiptCapsule); + when(trace.getRuntime()).thenReturn(runtime); + when(runtime.getResult()).thenReturn(programResult); + + transactionCapsule.setTrxTrace(trace); + + TransactionLogTriggerCapsule triggerCapsule = new TransactionLogTriggerCapsule( + transactionCapsule, blockCapsule,0,0,0, + builder.build(),0); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger()); + } + + @Test + public void testGetInternalTransactionList() throws Exception { + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract); + InternalTransaction internalTransaction = new InternalTransaction( + "parentHash".getBytes(), 10, 0, + "sendAddress".getBytes(), + "transferToAddress".getBytes(), + 100L, "data".getBytes(), "note", + 0L, new HashMap<>() + ); + List internalTransactionList = new ArrayList<>(); + internalTransactionList.add(internalTransaction); + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Method privateMethod = TransactionLogTriggerCapsule.class.getDeclaredMethod( + "getInternalTransactionList", List.class); + privateMethod.setAccessible(true); + List pojoList = (List) + privateMethod.invoke(triggerCapsule, internalTransactionList); + + Assert.assertNotNull(pojoList); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java index 76dd6e99158..a2487ac470b 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java @@ -13,13 +13,16 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.p2p.utils.ByteArray; import org.tron.protos.Protocol; +import org.tron.protos.contract.AssetIssueContractOuterClass; import org.tron.protos.contract.BalanceContract; import org.tron.protos.contract.Common; +import org.tron.protos.contract.SmartContractOuterClass; public class TransactionLogTriggerCapsuleTest { private static final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; private static final String RECEIVER_ADDRESS = "41abd4b9367799eaa3197fecb144eb71de1e049150"; + private static final String CONTRACT_ADDRESS = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; public TransactionCapsule transactionCapsule; public BlockCapsule blockCapsule; @@ -175,4 +178,70 @@ public void testConstructorWithCancelAllUnfreezeTrxCapsule() { triggerCapsule.getTransactionLogTrigger().getExtMap().get(BANDWIDTH.name()).longValue()); } + + @Test + public void testConstructorWithTransferCapsule() { + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + } + + @Test + public void testConstructorWithTransferAssetCapsule() { + AssetIssueContractOuterClass.TransferAssetContract.Builder builder2 = + AssetIssueContractOuterClass.TransferAssetContract.newBuilder() + .setAssetName(ByteString.copyFrom("AssetName".getBytes())) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferAssetContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + } + + @Test + public void testConstructorWithTriggerSmartContract() { + SmartContractOuterClass.TriggerSmartContract.Builder builder2 = + SmartContractOuterClass.TriggerSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(CONTRACT_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TriggerSmartContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + } + + @Test + public void testConstructorWithCreateSmartContract() { + SmartContractOuterClass.CreateSmartContract.Builder builder2 = + SmartContractOuterClass.CreateSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.CreateSmartContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + } + + + } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java new file mode 100644 index 00000000000..b9381df8460 --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java @@ -0,0 +1,54 @@ +package org.tron.common.runtime; + +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.vm.program.Program; + +import java.lang.reflect.Method; + +@Slf4j +public class RuntimeImplMockTest { + @After + public void clearMocks() { + + } + + @Test + public void testSetResultCode1() throws Exception { + RuntimeImpl runtime = new RuntimeImpl(); + ProgramResult programResult = new ProgramResult(); + Method privateMethod = RuntimeImpl.class.getDeclaredMethod( + "setResultCode", ProgramResult.class); + privateMethod.setAccessible(true); + + Program.BadJumpDestinationException badJumpDestinationException + = new Program.BadJumpDestinationException("Operation with pc isn't 'JUMPDEST': PC[%d];", 0); + programResult.setException(badJumpDestinationException); + privateMethod.invoke(runtime, programResult); + + Program.OutOfTimeException outOfTimeException + = new Program.OutOfTimeException("CPU timeout for 0x0a executing"); + programResult.setException(outOfTimeException); + privateMethod.invoke(runtime, programResult); + + Program.PrecompiledContractException precompiledContractException + = new Program.PrecompiledContractException("precompiled contract exception"); + programResult.setException(precompiledContractException); + privateMethod.invoke(runtime, programResult); + + Program.StackTooSmallException stackTooSmallException + = new Program.StackTooSmallException("Expected stack size %d but actual %d;", 100, 10); + programResult.setException(stackTooSmallException); + privateMethod.invoke(runtime, programResult); + + Program.JVMStackOverFlowException jvmStackOverFlowException + = new Program.JVMStackOverFlowException(); + programResult.setException(jvmStackOverFlowException); + privateMethod.invoke(runtime, programResult); + + Assert.assertTrue(true); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/WalletMockTest.java b/framework/src/test/java/org/tron/core/WalletMockTest.java new file mode 100644 index 00000000000..9dc0323f8fc --- /dev/null +++ b/framework/src/test/java/org/tron/core/WalletMockTest.java @@ -0,0 +1,1330 @@ +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.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.protobuf.LazyStringArrayList; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import com.google.protobuf.ProtocolStringList; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.api.GrpcAPI; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.client.WalletClient; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.ContractStateCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.db.Manager; +import org.tron.core.db.TransactionStore; +import org.tron.core.exception.AccountResourceInsufficientException; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.HeaderNotFound; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TronException; +import org.tron.core.exception.VMIllegalException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.exception.ZksnarkException; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.message.adv.TransactionMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.store.AbiStore; +import org.tron.core.store.AccountStore; +import org.tron.core.store.CodeStore; +import org.tron.core.store.ContractStateStore; +import org.tron.core.store.ContractStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.TransactionHistoryStore; +import org.tron.core.store.TransactionRetStore; +import org.tron.core.zen.ShieldedTRC20ParametersBuilder; +import org.tron.core.zen.address.DiversifierT; +import org.tron.core.zen.address.ExpandedSpendingKey; +import org.tron.core.zen.address.KeyIo; +import org.tron.core.zen.address.PaymentAddress; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.ShieldContract; +import org.tron.protos.contract.SmartContractOuterClass; + + +public class WalletMockTest { + + @Before + public void init() { + CommonParameter.PARAMETER.setMinEffectiveConnection(0); + } + + @After + public void clearMocks() { + Mockito.clearAllCaches(); + } + + @Test + public void testSetTransactionNullException() throws Exception { + Wallet wallet = new Wallet(); + TransactionCapsule transactionCapsuleMock + = mock(TransactionCapsule.class); + + Method privateMethod = Wallet.class.getDeclaredMethod( + "setTransaction", TransactionCapsule.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, transactionCapsuleMock); + + assertTrue(true); + } + + @Test + public void testCreateTransactionCapsuleWithoutValidateWithTimeoutNullException() + throws Exception { + Wallet wallet = new Wallet(); + com.google.protobuf.Message message = + mock(com.google.protobuf.Message.class); + Protocol.Transaction.Contract.ContractType contractType = + mock(Protocol.Transaction.Contract.ContractType.class); + long timeout = 100L; + + try (MockedConstruction mocked = mockConstruction(TransactionCapsule.class, + (mock, context) -> { + when(mock.getInstance()).thenReturn(Protocol.Transaction.newBuilder().build()); + })) { + Method privateMethod = Wallet.class.getDeclaredMethod( + "createTransactionCapsuleWithoutValidateWithTimeout", + com.google.protobuf.Message.class, + Protocol.Transaction.Contract.ContractType.class, + long.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, message, contractType, timeout); + assertTrue(true); + } + } + + @Test + public void testCreateTransactionCapsuleWithoutValidateWithTimeout() + throws Exception { + Wallet wallet = new Wallet(); + com.google.protobuf.Message message = + mock(com.google.protobuf.Message.class); + Protocol.Transaction.Contract.ContractType contractType = + mock(Protocol.Transaction.Contract.ContractType.class); + long timeout = 100L; + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + + try (MockedConstruction mocked = mockConstruction(TransactionCapsule.class, + (mock, context) -> { + when(mock.getInstance()).thenReturn(Protocol.Transaction.newBuilder().build()); + })) { + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + when(chainBaseManagerMock.getHeadBlockId()).thenReturn(blockId); + + Method privateMethod = Wallet.class.getDeclaredMethod( + "createTransactionCapsuleWithoutValidateWithTimeout", + com.google.protobuf.Message.class, + Protocol.Transaction.Contract.ContractType.class, + long.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, message, contractType, timeout); + + assertTrue(true); + } + } + + + @Test + public void testBroadcastTransactionBlockUnsolidified() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(true); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.BLOCK_UNSOLIDIFIED, ret.getCode()); + } + + @Test + public void testBroadcastTransactionNoConnection() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + List peerConnections = new ArrayList<>(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("minEffectiveConnection"); + field2.setAccessible(true); + field2.set(wallet, 10); + + when(tronNetDelegateMock.getActivePeer()).thenReturn(peerConnections); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.NO_CONNECTION, ret.getCode()); + } + + @Test + public void testBroadcastTransactionConnectionNotEnough() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + List peerConnections = new ArrayList<>(); + PeerConnection p1 = new PeerConnection(); + PeerConnection p2 = new PeerConnection(); + peerConnections.add(p1); + peerConnections.add(p2); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("minEffectiveConnection"); + field2.setAccessible(true); + field2.set(wallet, 10); + when(tronNetDelegateMock.getActivePeer()).thenReturn(peerConnections); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.NOT_ENOUGH_EFFECTIVE_CONNECTION, + ret.getCode()); + } + + @Test + public void testBroadcastTransactionTooManyPending() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(true); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.SERVER_BUSY, ret.getCode()); + } + + @Test + public void testBroadcastTransactionAlreadyExists() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + trx.setTime(System.currentTimeMillis()); + Sha256Hash txID = trx.getTransactionId(); + + Cache transactionIdCache = CacheBuilder + .newBuilder().maximumSize(10) + .expireAfterWrite(1, TimeUnit.HOURS).recordStats().build(); + transactionIdCache.put(txID, true); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(managerMock.getTransactionIdCache()).thenReturn(transactionIdCache); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, true); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.DUP_TRANSACTION_ERROR, + ret.getCode()); + } + + + @Test + public void testBroadcastTransactionNoContract() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock + = mock(DynamicPropertiesStore.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(dynamicPropertiesStoreMock); + when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field4 = wallet.getClass().getDeclaredField("chainBaseManager"); + field4.setAccessible(true); + field4.set(wallet, chainBaseManagerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, false); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR, + ret.getCode()); + } + + @Test + public void testBroadcastTransactionOtherException() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock + = mock(DynamicPropertiesStore.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(dynamicPropertiesStoreMock); + when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field4 = wallet.getClass().getDeclaredField("chainBaseManager"); + field4.setAccessible(true); + field4.set(wallet, chainBaseManagerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, false); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.OTHER_ERROR, ret.getCode()); + } + + private Protocol.Transaction getExampleTrans() { + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6666; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + return Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract( + Protocol.Transaction.Contract.newBuilder() + .setParameter(Any.pack(transferContract)) + .setType(Protocol.Transaction.Contract.ContractType.TransferContract))) + .build(); + } + + private void mockEnv(Wallet wallet, TronException tronException) throws Exception { + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + ChainBaseManager chainBaseManagerMock + = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock + = mock(DynamicPropertiesStore.class); + + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(dynamicPropertiesStoreMock); + when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); + + doThrow(tronException).when(managerMock).pushTransaction(any()); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field4 = wallet.getClass().getDeclaredField("chainBaseManager"); + field4.setAccessible(true); + field4.set(wallet, chainBaseManagerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, false); + } + + @Test + public void testBroadcastTransactionValidateSignatureException() throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new ValidateSignatureException()); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.SIGERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateContractExeException() throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new ContractExeException()); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.CONTRACT_EXE_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateAccountResourceInsufficientException() + throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new AccountResourceInsufficientException("")); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.BANDWITH_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateDupTransactionException() + throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new DupTransactionException("")); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.DUP_TRANSACTION_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateTaposException() throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new TaposException("")); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.TAPOS_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateTooBigTransactionException() + throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new TooBigTransactionException("")); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.TOO_BIG_TRANSACTION_ERROR, ret.getCode()); + } + + } + + @Test + public void testGetBlockByNum() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockByNum(anyLong()); + + Protocol.Block block = wallet.getBlockByNum(0L); + assertNull(block); + } + + @Test + public void testGetBlockCapsuleByNum() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockByNum(anyLong()); + + BlockCapsule blockCapsule = wallet.getBlockCapsuleByNum(0L); + assertNull(blockCapsule); + } + + @Test + public void testGetTransactionCountByBlockNum() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockByNum(anyLong()); + + long count = wallet.getTransactionCountByBlockNum(0L); + assertEquals(count, 0L); + } + + @Test + public void testGetTransactionById() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = null; + Protocol.Transaction transaction = wallet.getTransactionById(transactionId); + assertNull(transaction); + } + + @Test + public void testGetTransactionById2() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new BadItemException()).when(transactionStoreMock).get(any()); + + Protocol.Transaction transaction = wallet.getTransactionById(transactionId); + assertNull(transaction); + } + + @Test + public void testGetTransactionById3() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + TransactionCapsule transactionCapsuleMock = mock(TransactionCapsule.class); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(transactionStoreMock.get(any())).thenReturn(transactionCapsuleMock); + when(transactionCapsuleMock.getInstance()).thenReturn(transaction); + + Protocol.Transaction transactionRet = wallet.getTransactionById(transactionId); + assertEquals(transaction, transactionRet); + } + + @Test + public void testGetTransactionCapsuleById() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = null; + TransactionCapsule transactionCapsule = wallet.getTransactionCapsuleById(transactionId); + assertNull(transactionCapsule); + } + + @Test + public void testGetTransactionCapsuleById1() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new BadItemException()).when(transactionStoreMock).get(any()); + + TransactionCapsule transactionCapsule = wallet.getTransactionCapsuleById(transactionId); + assertNull(transactionCapsule); + } + + @Test + public void testGetTransactionInfoById() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = null; + Protocol.TransactionInfo transactionInfo = wallet.getTransactionInfoById(transactionId); + assertNull(transactionInfo); + } + + @Test + public void testGetTransactionInfoById1() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionRetStore transactionRetStoreMock = mock(TransactionRetStore.class); + + when(chainBaseManagerMock.getTransactionRetStore()).thenReturn(transactionRetStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new BadItemException()).when(transactionRetStoreMock).getTransactionInfo(any()); + + Protocol.TransactionInfo transactionInfo = wallet.getTransactionInfoById(transactionId); + assertNull(transactionInfo); + } + + @Test + public void testGetTransactionInfoById2() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionRetStore transactionRetStoreMock = mock(TransactionRetStore.class); + TransactionHistoryStore transactionHistoryStoreMock = + mock(TransactionHistoryStore.class); + + when(chainBaseManagerMock.getTransactionRetStore()) + .thenReturn(transactionRetStoreMock); + when(chainBaseManagerMock.getTransactionHistoryStore()) + .thenReturn(transactionHistoryStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(transactionRetStoreMock.getTransactionInfo(any())).thenReturn(null); + doThrow(new BadItemException()).when(transactionHistoryStoreMock).get(any()); + + Protocol.TransactionInfo transactionInfo = wallet.getTransactionInfoById(transactionId); + assertNull(transactionInfo); + } + + @Test + public void testGetProposalById() throws Exception { + Wallet wallet = new Wallet(); + ByteString proposalId = null; + Protocol.Proposal proposal = wallet.getProposalById(proposalId); + assertNull(proposal); + } + + @Test + public void testGetMemoFeePrices() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found MEMO_FEE_HISTORY")) + .when(dynamicPropertiesStoreMock).getMemoFeeHistory(); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + GrpcAPI.PricesResponseMessage responseMessage = wallet.getMemoFeePrices(); + assertNull(responseMessage); + } + + @Test + public void testGetEnergyFeeByTime() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + long now = System.currentTimeMillis(); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found ENERGY_PRICE_HISTORY")) + .when(dynamicPropertiesStoreMock).getEnergyPriceHistory(); + when(dynamicPropertiesStoreMock.getEnergyFee()).thenReturn(10L); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + long energyFee = wallet.getEnergyFee(now); + assertEquals(energyFee, 10L); + } + + @Test + public void testGetEnergyPrices() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found ENERGY_PRICE_HISTORY")) + .when(dynamicPropertiesStoreMock).getEnergyPriceHistory(); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + GrpcAPI.PricesResponseMessage pricesResponseMessage = wallet.getEnergyPrices(); + assertNull(pricesResponseMessage); + } + + @Test + public void testGetBandwidthPrices() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found BANDWIDTH_PRICE_HISTORY")) + .when(dynamicPropertiesStoreMock).getBandwidthPriceHistory(); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + GrpcAPI.PricesResponseMessage pricesResponseMessage = wallet.getBandwidthPrices(); + assertNull(pricesResponseMessage); + } + + @Test + public void testCheckBlockIdentifier() { + Wallet wallet = new Wallet(); + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .build(); + blockIdentifier = blockIdentifier.getDefaultInstanceForType(); + + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier1 = + blockIdentifier; + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkBlockIdentifier(blockIdentifier1); + }); + + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier2 = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setNumber(-1L) + .build(); + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkBlockIdentifier(blockIdentifier2); + }); + + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier3 = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(ByteString.copyFrom("".getBytes(StandardCharsets.UTF_8))) + .build(); + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkBlockIdentifier(blockIdentifier3); + }); + } + + @Test + public void testCheckAccountIdentifier() { + Wallet wallet = new Wallet(); + BalanceContract.AccountIdentifier accountIdentifier = + BalanceContract.AccountIdentifier.newBuilder().build(); + accountIdentifier = accountIdentifier.getDefaultInstanceForType(); + + BalanceContract.AccountIdentifier accountIdentifier2 = accountIdentifier; + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkAccountIdentifier(accountIdentifier2); + }); + + BalanceContract.AccountIdentifier accountIdentifier1 + = BalanceContract.AccountIdentifier.newBuilder().build(); + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkAccountIdentifier(accountIdentifier1); + }); + } + + @Test + public void testGetTriggerInputForShieldedTRC20Contract() { + Wallet wallet = new Wallet(); + GrpcAPI.ShieldedTRC20TriggerContractParameters.Builder triggerParam = + GrpcAPI.ShieldedTRC20TriggerContractParameters + .newBuilder(); + GrpcAPI.ShieldedTRC20Parameters shieldedTRC20Parameters = + GrpcAPI.ShieldedTRC20Parameters.newBuilder().build(); + GrpcAPI.BytesMessage bytesMessage = + GrpcAPI.BytesMessage.newBuilder().build(); + + triggerParam.setShieldedTRC20Parameters(shieldedTRC20Parameters); + triggerParam.addSpendAuthoritySignature(bytesMessage); + + CommonParameter commonParameterMock = mock(Args.class); + try (MockedStatic mockedStatic = mockStatic(CommonParameter.class)) { + when(CommonParameter.getInstance()).thenReturn(commonParameterMock); + when(commonParameterMock.isFullNodeAllowShieldedTransactionArgs()).thenReturn(true); + + assertThrows(ZksnarkException.class, () -> { + wallet.getTriggerInputForShieldedTRC20Contract(triggerParam.build()); + }); + } + } + + @Test + public void testGetTriggerInputForShieldedTRC20Contract1() + throws ZksnarkException, ContractValidateException { + Wallet wallet = new Wallet(); + ShieldContract.SpendDescription spendDescription = + ShieldContract.SpendDescription.newBuilder().build(); + GrpcAPI.ShieldedTRC20TriggerContractParameters.Builder triggerParam = + GrpcAPI.ShieldedTRC20TriggerContractParameters + .newBuilder(); + GrpcAPI.ShieldedTRC20Parameters shieldedTRC20Parameters = + GrpcAPI.ShieldedTRC20Parameters.newBuilder() + .addSpendDescription(spendDescription) + .setParameterType("transfer") + .build(); + GrpcAPI.BytesMessage bytesMessage = + GrpcAPI.BytesMessage.newBuilder().build(); + + triggerParam.setShieldedTRC20Parameters(shieldedTRC20Parameters); + triggerParam.addSpendAuthoritySignature(bytesMessage); + + CommonParameter commonParameterMock = mock(Args.class); + try (MockedStatic mockedStatic = mockStatic(CommonParameter.class)) { + when(CommonParameter.getInstance()).thenReturn(commonParameterMock); + when(commonParameterMock.isFullNodeAllowShieldedTransactionArgs()).thenReturn(true); + + GrpcAPI.BytesMessage reponse = + wallet.getTriggerInputForShieldedTRC20Contract(triggerParam.build()); + assertNotNull(reponse); + } + + } + + @Test + public void testGetShieldedContractScalingFactorException() throws Exception { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + when(walletMock.createTransactionCapsule(any(), any())) + .thenReturn(new TransactionCapsule(transaction)); + + try { + when(walletMock.getShieldedContractScalingFactor(contractAddress)).thenCallRealMethod(); + } catch (Exception e) { + assertNotNull(e); + } + } + + @Test + public void testGetShieldedContractScalingFactorRuntimeException() + throws VMIllegalException, HeaderNotFound, ContractValidateException, ContractExeException { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + when(walletMock.triggerConstantContract(any(),any(),any(),any())).thenReturn(transaction); + when(walletMock.getShieldedContractScalingFactor(any())).thenCallRealMethod(); + + assertThrows(ContractExeException.class, () -> { + walletMock.getShieldedContractScalingFactor(contractAddress); + }); + } + + @Test + public void testGetShieldedContractScalingFactorSuccess() + throws Exception { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + when(walletMock.triggerConstantContract(any(),any(),any(),any())) + .thenReturn(transaction); + when(walletMock.createTransactionCapsule(any(), any())) + .thenReturn(new TransactionCapsule(transaction)); + when(walletMock.getShieldedContractScalingFactor(any())).thenCallRealMethod(); + try { + byte[] listBytes = walletMock.getShieldedContractScalingFactor(contractAddress); + assertNotNull(listBytes); + } catch (Exception e) { + assertNull(e); + } + } + + @Test + public void testGetShieldedContractScalingFactorContractExeException() + throws Exception { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + doThrow(new ContractExeException("")) + .when(walletMock).triggerConstantContract(any(),any(),any(),any()); + when(walletMock.createTransactionCapsule(any(), any())) + .thenReturn(new TransactionCapsule(transaction)); + when(walletMock.getShieldedContractScalingFactor(any())).thenCallRealMethod(); + + assertThrows(ContractExeException.class, () -> { + walletMock.getShieldedContractScalingFactor(contractAddress); + }); + } + + @Test + public void testCheckBigIntegerRange() { + Wallet wallet = new Wallet(); + + assertThrows( + Exception.class, + () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkBigIntegerRange", BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, new BigInteger("-1")); + } + ); + } + + @Test + public void testCheckPublicAmount() throws ContractExeException { + Wallet walletMock = mock(Wallet.class); + + byte[] address = "".getBytes(StandardCharsets.UTF_8); + BigInteger fromAmount = new BigInteger("10"); + BigInteger toAmount = new BigInteger("10"); + doThrow(new ContractExeException("")).when(walletMock).getShieldedContractScalingFactor(any()); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkPublicAmount", + byte[].class, BigInteger.class, BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(walletMock, address, fromAmount, toAmount); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractExeException); + } + + @Test + public void testCheckPublicAmount1() throws ContractExeException { + Wallet walletMock = mock(Wallet.class); + + byte[] address = "".getBytes(StandardCharsets.UTF_8); + BigInteger fromAmount = new BigInteger("300"); + BigInteger toAmount = new BigInteger("255"); + + byte[] scalingFactorBytes = ByteUtil.bigIntegerToBytes(new BigInteger("-1")); + + when(walletMock.getShieldedContractScalingFactor(any())).thenReturn(scalingFactorBytes); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkPublicAmount", + byte[].class, BigInteger.class, BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(walletMock, address, fromAmount, toAmount); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractValidateException); + } + + @Test + public void testCheckPublicAmount2() throws ContractExeException { + Wallet walletMock = mock(Wallet.class); + + byte[] address = "".getBytes(StandardCharsets.UTF_8); + BigInteger fromAmount = new BigInteger("300"); + BigInteger toAmount = new BigInteger("255"); + + byte[] scalingFactorBytes = ByteUtil.bigIntegerToBytes(new BigInteger("-1")); + try (MockedStatic mockedStatic = mockStatic(ByteUtil.class)) { + when(ByteUtil.bytesToBigInteger(any())).thenReturn(new BigInteger("-1")); + when(walletMock.getShieldedContractScalingFactor(any())).thenReturn(scalingFactorBytes); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkPublicAmount", + byte[].class, BigInteger.class, BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(walletMock, address, fromAmount, toAmount); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractValidateException); + } + + } + + @Test + public void testGetShieldedTRC20Nullifier() { + Wallet wallet = new Wallet(); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + long pos = 100L; + byte[] ak = "ak".getBytes(StandardCharsets.UTF_8); + byte[] nk = "nk".getBytes(StandardCharsets.UTF_8); + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(null); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20Nullifier", + GrpcAPI.Note.class, long.class, byte[].class, + byte[].class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + note, pos, ak, nk); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ZksnarkException); + } + } + + @Test + public void testGetShieldedTRC20LogType() { + Wallet wallet = new Wallet(); + Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder().build(); + byte[] contractAddress = "contractAddress".getBytes(StandardCharsets.UTF_8); + LazyStringArrayList topicsList = new LazyStringArrayList(); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20LogType", + Protocol.TransactionInfo.Log.class, + byte[].class, + ProtocolStringList.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + log, + contractAddress, + topicsList); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ZksnarkException); + } + + @Test + public void testGetShieldedTRC20LogType1() { + Wallet wallet = new Wallet(); + final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; + byte[] contractAddress = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); + + byte[] addressWithoutPrefix = new byte[20]; + System.arraycopy(contractAddress, 1, addressWithoutPrefix, 0, 20); + Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom(addressWithoutPrefix)) + .build(); + + LazyStringArrayList topicsList = new LazyStringArrayList(); + try { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20LogType", + Protocol.TransactionInfo.Log.class, + byte[].class, + ProtocolStringList.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + log, + contractAddress, + topicsList); + } catch (Exception e) { + assertTrue(false); + } + assertTrue(true); + } + + + @Test + public void testGetShieldedTRC20LogType2() { + Wallet wallet = new Wallet(); + final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; + byte[] contractAddress = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); + + byte[] addressWithoutPrefix = new byte[20]; + System.arraycopy(contractAddress, 1, addressWithoutPrefix, 0, 20); + Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom(addressWithoutPrefix)) + .addTopics(ByteString.copyFrom("topic".getBytes())) + .build(); + + LazyStringArrayList topicsList = new LazyStringArrayList(); + topicsList.add("topic"); + try { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20LogType", + Protocol.TransactionInfo.Log.class, + byte[].class, + ProtocolStringList.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + log, + contractAddress, + topicsList); + } catch (Exception e) { + assertTrue(false); + } + assertTrue(true); + } + + @Test + public void testBuildShieldedTRC20InputWithAK() throws ZksnarkException { + Wallet wallet = new Wallet(); + ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder("transfer"); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + GrpcAPI.SpendNoteTRC20 spendNote = GrpcAPI.SpendNoteTRC20.newBuilder() + .setNote(note) + .setAlpha(ByteString.copyFrom("alpha".getBytes())) + .setRoot(ByteString.copyFrom("root".getBytes())) + .setPath(ByteString.copyFrom("path".getBytes())) + .setPos(0L) + .build(); + byte[] ak = "ak".getBytes(StandardCharsets.UTF_8); + byte[] nk = "nk".getBytes(StandardCharsets.UTF_8); + + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(null); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "buildShieldedTRC20InputWithAK", + ShieldedTRC20ParametersBuilder.class, + GrpcAPI.SpendNoteTRC20.class, + byte[].class, byte[].class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + builder, + spendNote, + ak, nk); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ZksnarkException); + } + + } + + @Test + public void testBuildShieldedTRC20InputWithAK1() throws Exception { + Wallet wallet = new Wallet(); + ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder("transfer"); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + GrpcAPI.SpendNoteTRC20 spendNote = GrpcAPI.SpendNoteTRC20.newBuilder() + .setNote(note) + .setAlpha(ByteString.copyFrom("alpha".getBytes())) + .setRoot(ByteString.copyFrom("root".getBytes())) + .setPath(ByteString.copyFrom("path".getBytes())) + .setPos(0L) + .build(); + byte[] ak = "ak".getBytes(StandardCharsets.UTF_8); + byte[] nk = "nk".getBytes(StandardCharsets.UTF_8); + PaymentAddress paymentAddress = mock(PaymentAddress.class); + DiversifierT diversifierT = mock(DiversifierT.class); + + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(paymentAddress); + when(paymentAddress.getD()).thenReturn(diversifierT); + when(paymentAddress.getPkD()).thenReturn("pkd".getBytes()); + + Method privateMethod = Wallet.class.getDeclaredMethod( + "buildShieldedTRC20InputWithAK", + ShieldedTRC20ParametersBuilder.class, + GrpcAPI.SpendNoteTRC20.class, + byte[].class, byte[].class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + builder, + spendNote, + ak, nk); + assertTrue(true); + } + + } + + @Test + public void testBuildShieldedTRC20Input() throws Exception { + Wallet wallet = new Wallet(); + ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder("transfer"); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + GrpcAPI.SpendNoteTRC20 spendNote = GrpcAPI.SpendNoteTRC20.newBuilder() + .setNote(note) + .setAlpha(ByteString.copyFrom("alpha".getBytes())) + .setRoot(ByteString.copyFrom("root".getBytes())) + .setPath(ByteString.copyFrom("path".getBytes())) + .setPos(0L) + .build(); + ExpandedSpendingKey expandedSpendingKey = mock(ExpandedSpendingKey.class); + PaymentAddress paymentAddress = mock(PaymentAddress.class); + DiversifierT diversifierT = mock(DiversifierT.class); + + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(paymentAddress); + when(paymentAddress.getD()).thenReturn(diversifierT); + when(paymentAddress.getPkD()).thenReturn("pkd".getBytes()); + Method privateMethod = Wallet.class.getDeclaredMethod( + "buildShieldedTRC20Input", + ShieldedTRC20ParametersBuilder.class, + GrpcAPI.SpendNoteTRC20.class, + ExpandedSpendingKey.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + builder, + spendNote, + expandedSpendingKey); + } + } + + @Test + public void testGetContractInfo() throws Exception { + Wallet wallet = new Wallet(); + GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() + .setValue(ByteString.copyFrom("test".getBytes())) + .build(); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + AccountStore accountStore = mock(AccountStore.class); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(chainBaseManagerMock.getAccountStore()).thenReturn(accountStore); + when(accountStore.get(any())).thenReturn(null); + + SmartContractOuterClass.SmartContractDataWrapper smartContractDataWrapper = + wallet.getContractInfo(bytesMessage); + assertNull(smartContractDataWrapper); + } + + @Test + public void testGetContractInfo1() throws Exception { + Wallet wallet = new Wallet(); + GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() + .setValue(ByteString.copyFrom("test".getBytes())) + .build(); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + AccountStore accountStore = mock(AccountStore.class); + ContractStore contractStore = mock(ContractStore.class); + AbiStore abiStore = mock(AbiStore.class); + CodeStore codeStore = mock(CodeStore.class); + ContractStateStore contractStateStore = mock(ContractStateStore.class); + DynamicPropertiesStore dynamicPropertiesStore = mock(DynamicPropertiesStore.class); + + AccountCapsule accountCapsule = mock(AccountCapsule.class); + ContractCapsule contractCapsule = mock(ContractCapsule.class); + ContractStateCapsule contractStateCapsule = new ContractStateCapsule(10L); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(chainBaseManagerMock.getAccountStore()).thenReturn(accountStore); + when(chainBaseManagerMock.getContractStore()).thenReturn(contractStore); + when(chainBaseManagerMock.getAbiStore()).thenReturn(abiStore); + when(chainBaseManagerMock.getCodeStore()).thenReturn(codeStore); + when(chainBaseManagerMock.getContractStateStore()).thenReturn(contractStateStore); + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStore); + + when(accountStore.get(any())).thenReturn(accountCapsule); + when(contractStore.get(any())).thenReturn(contractCapsule); + when(contractCapsule.generateWrapper()) + .thenReturn(SmartContractOuterClass.SmartContractDataWrapper.newBuilder().build()); + when(abiStore.get(any())).thenReturn(null); + when(codeStore.get(any())).thenReturn(null); + when(contractStateStore.get(any())).thenReturn(contractStateCapsule); + when(dynamicPropertiesStore.getCurrentCycleNumber()).thenReturn(100L); + + SmartContractOuterClass.SmartContractDataWrapper smartContractDataWrapper = + wallet.getContractInfo(bytesMessage); + assertNotNull(smartContractDataWrapper); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/ManagerMockTest.java b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java new file mode 100644 index 00000000000..ff6e0dce3d8 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java @@ -0,0 +1,447 @@ +package org.tron.core.db; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; + +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import org.quartz.CronExpression; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.ProgramResult; +import org.tron.common.runtime.RuntimeImpl; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.capsule.TransactionInfoCapsule; +import org.tron.core.capsule.utils.TransactionUtil; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractSizeNotEqualToOneException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TooBigTransactionResultException; +import org.tron.core.exception.TransactionExpirationException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.BalanceTraceStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +@Slf4j +public class ManagerMockTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + @Test + public void processTransactionCostTimeMoreThan100() throws Exception { + TransactionTrace traceMock = mock(TransactionTrace.class); + BandwidthProcessor bandwidthProcessorMock = mock(BandwidthProcessor.class); + try (MockedConstruction mockedConstruction2 = mockConstruction(TransactionTrace.class,(mock, context) -> { + when(mock).thenReturn(traceMock); + }); + MockedConstruction mockedConstruction3 = mockConstruction(BandwidthProcessor.class,(mock, context) -> { + when(mock).thenReturn(bandwidthProcessorMock); + }); + MockedStatic mockedStatic = mockStatic(TransactionUtil.class)) { + Manager dbManager = mock(Manager.class); + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6666; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract( + Protocol.Transaction.Contract.newBuilder() + .setParameter(Any.pack(transferContract)) + .setType(Protocol.Transaction.Contract.ContractType.TransferContract))) + .build(); + TransactionCapsule trxCap = new TransactionCapsule(transaction); + ProgramResult result = new ProgramResult(); + result.setResultCode(Protocol.Transaction.Result.contractResult.SUCCESS); + + Sha256Hash transactionId = trxCap.getTransactionId(); + TransactionCapsule trxCapMock = mock(TransactionCapsule.class); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + BalanceTraceStore balanceTraceStoreMock = mock(BalanceTraceStore.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + TransactionInfoCapsule transactionInfoCapsuleMock = mock(TransactionInfoCapsule.class); + Protocol.TransactionInfo transactionInfo = Protocol.TransactionInfo.newBuilder().build(); + + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + + BlockCapsule blockCapMock = Mockito.mock(BlockCapsule.class); + + when(TransactionUtil + .buildTransactionInfoInstance(trxCapMock, blockCapMock, traceMock)) + .thenReturn(transactionInfoCapsuleMock); + + // this make cost > 100 cond is true + when(blockCapMock.isMerkleRootEmpty()).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + Thread.sleep(100); + return true; + } + }); + + when(chainBaseManagerMock.getBalanceTraceStore()).thenReturn(balanceTraceStoreMock); + when(chainBaseManagerMock.getAccountStore()).thenReturn(mock(AccountStore.class)); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(mock(DynamicPropertiesStore.class)); + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + when(trxCapMock.getTransactionId()).thenReturn(transactionId); + when(traceMock.getRuntimeResult()).thenReturn(result); + when(transactionInfoCapsuleMock.getId()).thenReturn(transactionId.getBytes()); + when(transactionInfoCapsuleMock.getInstance()).thenReturn(transactionInfo); + when(trxCapMock.getInstance()).thenReturn(trxCap.getInstance()); + when(trxCapMock.validatePubSignature( + Mockito.any(AccountStore.class), + Mockito.any(DynamicPropertiesStore.class))).thenReturn(true); + when(trxCapMock.validateSignature( + Mockito.any(AccountStore.class), + Mockito.any(DynamicPropertiesStore.class))).thenReturn(true); + + doNothing().when(dbManager).validateTapos(trxCapMock); + doNothing().when(dbManager).validateCommon(trxCapMock); + doNothing().when(dbManager).validateDup(trxCapMock); + + + doNothing().when(transactionStoreMock).put(transactionId.getBytes(), trxCapMock); + doNothing().when(bandwidthProcessorMock).consume(trxCapMock, traceMock); + doNothing().when(dbManager).consumeBandwidth(trxCapMock, traceMock); + doNothing().when(balanceTraceStoreMock).initCurrentTransactionBalanceTrace(trxCapMock); + doNothing().when(balanceTraceStoreMock).updateCurrentTransactionStatus(anyString()); + doNothing().when(balanceTraceStoreMock).resetCurrentTransactionTrace(); + + + assertNotNull( + when(dbManager.processTransaction(trxCapMock, blockCapMock)).thenCallRealMethod() + ); + } + } + + private void initMockEnv(Manager dbManager, long headNum, long headTime, + long exitHeight, long exitCount, String blockTime) + throws Exception { + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Args argsMock = mock(Args.class); + + when(Args.getInstance()).thenReturn(argsMock); + + when(chainBaseManagerMock.getHeadBlockNum()).thenReturn(headNum); + when(chainBaseManagerMock.getHeadBlockTimeStamp()).thenReturn(headTime); + + when(argsMock.getShutdownBlockHeight()).thenReturn(exitHeight); + when(argsMock.getShutdownBlockCount()).thenReturn(exitCount); + when(argsMock.isP2pDisable()).thenReturn(false); + when(argsMock.getShutdownBlockTime()) + .thenReturn(new CronExpression(blockTime)); //"0 0 12 * * ?" + + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + } + + @Test + public void testInitAutoStop() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager, 100L, 12345L, + 10L, 0L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockHeight 10 is less than headNum 100", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop1() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 12345L, + 100L, 0L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockCount 0 is less than 1", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + } + + @Test + public void testInitAutoStop2() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 99726143865000L, + 100L, 1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockTime 0 0 12 * * ? is illegal", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop3() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 12345L, + 100L, 1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockHeight 100 and shutDownBlockCount 1 set both", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop4() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager, 10L, 12345L, + 100L, -1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockHeight 100 and shutDownBlockTime 0 0 12 * * ? set both", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop5() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 12345L, + 0L, 1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockCount 1 and shutDownBlockTime 0 0 12 * * ? set both", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testProcessTransaction() throws Exception { + Manager dbManager = spy(new Manager()); + TransactionCapsule transactionCapsuleMock = null; + BlockCapsule blockCapsuleMock = mock(BlockCapsule.class); + + Method privateMethod = Manager.class.getDeclaredMethod( + "processTransaction", + TransactionCapsule.class, BlockCapsule.class); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager, transactionCapsuleMock, blockCapsuleMock); + + assertTrue(true); + } + + @Test + public void testProcessTransaction1() { + Manager dbManager = spy(new Manager()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder() + .setData(ByteString.copyFrom("sb.toString()".getBytes(StandardCharsets.UTF_8)))) + .build(); + TransactionCapsule trxCap = new TransactionCapsule(transaction); + + BlockCapsule blockCapsuleMock = mock(BlockCapsule.class); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "processTransaction", + TransactionCapsule.class, BlockCapsule.class); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager, trxCap, blockCapsuleMock); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractSizeNotEqualToOneException); + } + + @SneakyThrows + @Test + public void testRePush() { + Manager dbManager = spy(new Manager()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + when(transactionStoreMock.has(any())).thenReturn(true); + + dbManager.rePush(trx); + assertTrue(true); + } + + @SneakyThrows + @Test + public void testRePush1() { + Manager dbManager = spy(new Manager()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + when(transactionStoreMock.has(any())).thenReturn(false); + + doThrow(new ValidateSignatureException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new DupTransactionException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TaposException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TooBigTransactionException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TransactionExpirationException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new ReceiptCheckErrException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TooBigTransactionResultException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + assertTrue(true); + } + + @Test + public void testPostSolidityFilter() throws Exception { + Manager dbManager = spy(new Manager()); + + Method privateMethod = Manager.class.getDeclaredMethod( + "postSolidityFilter", long.class, long.class); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager, 100L, 10L); + assertTrue(true); + } + + @Test + public void testReOrgLogsFilter() throws Exception { + Manager dbManager = spy(new Manager()); + CommonParameter commonParameterMock = mock(Args.class); + mockStatic(CommonParameter.class); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + when(CommonParameter.getInstance()).thenReturn(commonParameterMock); + when(commonParameterMock.isJsonRpcHttpFullNodeEnable()).thenReturn(true); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(mock(DynamicPropertiesStore.class)); + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockById(any()); + + Method privateMethod = Manager.class.getDeclaredMethod("reOrgLogsFilter"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + assertTrue(true); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java new file mode 100644 index 00000000000..5e8c69fdd6a --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java @@ -0,0 +1,28 @@ +package org.tron.core.net.peer; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.spy; + +import org.junit.After; +import org.junit.Test; +import org.mockito.Mockito; + +public class PeerStatusCheckMockTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + @Test + public void testInitException() throws InterruptedException { + PeerStatusCheck peerStatusCheck = spy(new PeerStatusCheck()); + doThrow(new RuntimeException("test exception")).when(peerStatusCheck).statusCheck(); + peerStatusCheck.init(); + + // the initialDelay of scheduleWithFixedDelay is 5s + Thread.sleep(5000L); + assertTrue(true); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java b/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java new file mode 100644 index 00000000000..a8525b0f526 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java @@ -0,0 +1,255 @@ +package org.tron.core.services.http; + +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 com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; + +import java.io.CharArrayReader; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.protos.Protocol; + +public class JsonFormatTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + @Test + public void testPrintErrorMsg() { + Exception ex = new Exception("test"); + String out = JsonFormat.printErrorMsg(ex); + assertEquals("{\"Error\":\"test\"}", out); + } + + @Test + public void testPrintWithHelloMessage() throws IOException { + Protocol.HelloMessage message = Protocol.HelloMessage.newBuilder() + .setAddress(ByteString.copyFrom("address".getBytes())) + .build(); + StringWriter output = new StringWriter(); + + JsonFormat.print(message, output, true); + assertNotNull(output.toString()); + } + + private UnknownFieldSet createValidUnknownFieldSet() { + UnknownFieldSet unknownFieldSet2 = UnknownFieldSet.newBuilder().build(); + UnknownFieldSet.Field unknownField1 = UnknownFieldSet.Field.newBuilder() + .addFixed32(123) + .addFixed64(12345L) + .addGroup(unknownFieldSet2) + .addLengthDelimited(ByteString.copyFrom("length".getBytes())) + .addVarint(12345678L) + .build(); + + return UnknownFieldSet.newBuilder() + .addField(1, unknownField1) + .build(); + } + + @Test + public void testPrintWithFields() throws IOException { + UnknownFieldSet unknownFieldSet = createValidUnknownFieldSet(); + StringWriter output = new StringWriter(); + JsonFormat.print(unknownFieldSet, output, true); + assertNotNull(output.toString()); + } + + @Test + public void testPrintToString() { + UnknownFieldSet unknownFieldSet = createValidUnknownFieldSet(); + String output = JsonFormat.printToString(unknownFieldSet, true); + assertNotNull(output); + } + + @Test + public void testUnsignedToString() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("unsignedToString", int.class); + privateMethod.setAccessible(true); + String out3 = (String)privateMethod.invoke(null, 100); + assertEquals("100", out3); + String out4 = (String)privateMethod.invoke(null, -100); + assertNotNull(out4); + } + + @Test + public void testToStringBuilderWithNonReadableInput() throws Exception { + String inputString = "Hello, World!"; + Readable input = new CharArrayReader(inputString.toCharArray()); + + Method privateMethod = JsonFormat.class.getDeclaredMethod("toStringBuilder", Readable.class); + privateMethod.setAccessible(true); + + StringBuilder out = (StringBuilder)privateMethod.invoke(null, input); + assertEquals(inputString, out.toString()); + } + + + @Test + public void testUnicodeEscaped() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("unicodeEscaped", char.class); + privateMethod.setAccessible(true); + + + char input1 = 0x09; + String out = (String)privateMethod.invoke(null, input1); + assertNotNull(out); + + char input2 = 0x99; + String out2 = (String)privateMethod.invoke(null, input2); + assertNotNull(out2); + + char input3 = 0x999; + String out3 = (String)privateMethod.invoke(null, input3); + assertNotNull(out3); + + char input4 = 0x1001; + String out4 = (String)privateMethod.invoke(null, input4); + assertNotNull(out4); + } + + @Test + public void testEscapeText() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("escapeText", String.class); + privateMethod.setAccessible(true); + + String input1 = "\b\f\n\r\t\\\"\\b\\f\\n\\r\\t\\\\\"test123"; + String out = (String)privateMethod.invoke(null, input1); + assertNotNull(out); + } + + @Test + public void testAppendEscapedUnicode() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("appendEscapedUnicode", + StringBuilder.class, char.class); + privateMethod.setAccessible(true); + + char input1 = 0x09; + StringBuilder out1 = new StringBuilder(); + + privateMethod.invoke(null, out1, input1); + assertNotNull(out1); + + char input2 = 0x99; + StringBuilder out2 = new StringBuilder(); + privateMethod.invoke(null, out2, input2); + assertNotNull(out2); + + char input3 = 0x999; + StringBuilder out3 = new StringBuilder(); + privateMethod.invoke(null, out3, input3); + assertNotNull(out3); + + char input4 = 0x1001; + StringBuilder out4 = new StringBuilder(); + privateMethod.invoke(null, out4, input4); + assertNotNull(out4); + } + + @Test + public void testUnescapeText() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("unescapeText", String.class); + privateMethod.setAccessible(true); + + String input = "\\u1234\\b\\f\\n\\r\\t\\\\\"test123";; + String out = (String)privateMethod.invoke(null, input); + assertNotNull(out); + } + + @Test + public void testDigitValue() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("digitValue", char.class); + privateMethod.setAccessible(true); + + char input = '1'; + int out = (int)privateMethod.invoke(null, input); + assertEquals(1, out); + + char input1 = 'b'; + int out1 = (int)privateMethod.invoke(null, input1); + assertEquals(11, out1); + + char input2 = 'B'; + int out2 = (int)privateMethod.invoke(null, input2); + assertEquals(11, out2); + } + + @Test + public void testParseUInt64() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("parseUInt64", String.class); + privateMethod.setAccessible(true); + + String input = "12312312312"; + long out = (long)privateMethod.invoke(null, input); + assertEquals(12312312312L, out); + + String input1 = "0x10"; + long out1 = (long)privateMethod.invoke(null, input1); + assertEquals(16L, out1); + + String input2 = "010"; + long out2 = (long)privateMethod.invoke(null, input2); + assertEquals(8L, out2); + + String input3 = "-12312312312"; + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null, input3); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + } + + @Test + public void testParseInteger() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("parseInteger", + String.class, boolean.class, boolean.class); + privateMethod.setAccessible(true); + + String input1 = "92233720368547758070"; + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input1, true, true); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input5 = "92233720368547758070"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input5, false, true); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input2 = "-92233720368547758"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input2, false, true); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input3 = "92233720368547758070"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input3, false, false); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input4 = "-92233720368547758070"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input4, true, false); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java b/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java new file mode 100644 index 00000000000..221c5a7a165 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java @@ -0,0 +1,243 @@ +package org.tron.core.services.http; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.api.GrpcAPI; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.p2p.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.SmartContractOuterClass; + +public class UtilMockTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + + @Test + public void testPrintTransactionFee() { + Protocol.ResourceReceipt resourceReceipt = Protocol.ResourceReceipt.newBuilder() + .build(); + Protocol.TransactionInfo result = Protocol.TransactionInfo.newBuilder() + .setReceipt(resourceReceipt) + .build(); + String transactionFee = JsonFormat.printToString(result, true); + String out = Util.printTransactionFee(transactionFee); + Assert.assertNotNull(out); + } + + @Test + public void testPrintBlockList() { + BlockCapsule blockCapsule1 = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + BlockCapsule blockCapsule2 = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + GrpcAPI.BlockList list = GrpcAPI.BlockList.newBuilder() + .addBlock(blockCapsule1.getInstance()) + .addBlock(blockCapsule2.getInstance()) + .build(); + String out = Util.printBlockList(list, true); + Assert.assertNotNull(out); + } + + @Test + public void testPrintTransactionList() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + GrpcAPI.TransactionList list = GrpcAPI.TransactionList.newBuilder() + .addTransaction(transactionCapsule.getInstance()) + .build(); + String out = Util.printTransactionList(list, true); + Assert.assertNotNull(out); + } + + private TransactionCapsule getTransactionCapsuleExample() { + final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + final String RECEIVER_ADDRESS = "41abd4b9367799eaa3197fecb144eb71de1e049150"; + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress( + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + return new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract); + } + + @Test + public void testPrintTransactionSignWeight() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + GrpcAPI.TransactionExtention transactionExtention = + GrpcAPI.TransactionExtention.newBuilder() + .setTransaction(transactionCapsule.getInstance()) + .build(); + GrpcAPI.TransactionSignWeight txSignWeight = + GrpcAPI.TransactionSignWeight.newBuilder() + .setTransaction(transactionExtention) + .build(); + + String out = Util.printTransactionSignWeight(txSignWeight, true); + Assert.assertNotNull(out); + } + + @Test + public void testPrintTransactionApprovedList() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + GrpcAPI.TransactionExtention transactionExtention = + GrpcAPI.TransactionExtention.newBuilder() + .setTransaction(transactionCapsule.getInstance()) + .build(); + GrpcAPI.TransactionApprovedList transactionApprovedList = + GrpcAPI.TransactionApprovedList.newBuilder() + .setTransaction(transactionExtention) + .build(); + String out = Util.printTransactionApprovedList( + transactionApprovedList, true); + Assert.assertNotNull(out); + } + + @Test + public void testGenerateContractAddress() { + final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + byte[] out = Util.generateContractAddress( + transactionCapsule.getInstance(), OWNER_ADDRESS.getBytes()); + Assert.assertNotNull(out); + } + + @Test + public void testPrintTransactionToJSON() { + final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + SmartContractOuterClass.CreateSmartContract.Builder builder2 = + SmartContractOuterClass.CreateSmartContract.newBuilder() + .setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + TransactionCapsule transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.CreateSmartContract); + + JSONObject out = Util.printTransactionToJSON( + transactionCapsule.getInstance(), true); + Assert.assertNotNull(out); + } + + @Test + public void testGetContractType() { + String out = Util.getContractType("{\"contractType\":\"123\"}\n"); + Assert.assertEquals("123", out); + } + + @Test + public void testGetHexAddress() { + String out = Util.getHexAddress("TBxSocpujP6UGKV5ydXNVTDQz7fAgdmoaB"); + Assert.assertNotNull(out); + + Assert.assertNull(Util.getHexAddress(null)); + } + + @Test + public void testSetTransactionPermissionId() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + Protocol.Transaction out = Util.setTransactionPermissionId( + 123, transactionCapsule.getInstance()); + Assert.assertNotNull(out); + } + + @Test + public void testSetTransactionExtraData() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + JSONObject jsonObject = JSONObject.parseObject("{\"extra_data\":\"test\"}"); + Protocol.Transaction out = Util.setTransactionExtraData(jsonObject, + transactionCapsule.getInstance(), true); + Assert.assertNotNull(out); + } + + @Test + public void testConvertOutput() { + Protocol.Account account = Protocol.Account.newBuilder().build(); + String out = Util.convertOutput(account); + Assert.assertNotNull(out); + + account = Protocol.Account.newBuilder() + .setAssetIssuedID(ByteString.copyFrom("asset_issued_ID".getBytes())) + .build(); + out = Util.convertOutput(account); + Assert.assertNotNull(out); + } + + @Test + public void testConvertLogAddressToTronAddress() { + List logs = new ArrayList<>(); + logs.add(Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom("address".getBytes())) + .setData(ByteString.copyFrom("data".getBytes())) + .addTopics(ByteString.copyFrom("topic".getBytes())) + .build()); + + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder() + .addAllLog(logs); + List logList = + Util.convertLogAddressToTronAddress(builder.build()); + Assert.assertNotNull(logList.size() > 0); + } + + @Test + public void testValidateParameter() { + String contract = "{\"address\":\"owner_address\"}"; + Assert.assertThrows( + InvalidParameterException.class, + () -> { + Util.validateParameter(contract); + } + ); + String contract1 = + "{\"owner_address\":\"owner_address\"," + + " \"contract_address1\":\"contract_address\", \"data1\":\"data\"}"; + Assert.assertThrows( + InvalidParameterException.class, + () -> { + Util.validateParameter(contract1); + } + ); + String contract2 = + "{\"owner_address\":\"owner_address\", " + + "\"function_selector\":\"function_selector\", \"data\":\"data\"}"; + Assert.assertThrows( + InvalidParameterException.class, + () -> { + Util.validateParameter(contract2); + } + ); + } + + @Test + public void testGetJsonString() { + String str = ""; + String ret = Util.getJsonString(str); + Assert.assertTrue(StringUtils.isEmpty(ret)); + + String str1 = "{\"owner_address\":\"owner_address\"}"; + String ret1 = Util.getJsonString(str1); + Assert.assertTrue(str1.equals(ret1)); + + String str2 = "owner_address=owner_address&contract_address=contract_address"; + String ret2 = Util.getJsonString(str2); + String expect = + "{\"owner_address\":\"owner_address\"," + + "\"contract_address\":\"contract_address\"}"; + Assert.assertEquals(expect, ret2); + } + +} \ No newline at end of file From e08511b68f47e0a6c53b166b44670ac17d327f02 Mon Sep 17 00:00:00 2001 From: chaozhu Date: Thu, 12 Dec 2024 23:51:34 +0800 Subject: [PATCH 3/4] fix check style error --- .../TransactionLogTriggerCapsuleMockTest.java | 7 ++++--- .../tron/common/runtime/RuntimeImplMockTest.java | 4 +++- .../src/test/java/org/tron/core/WalletMockTest.java | 2 +- .../test/java/org/tron/core/db/ManagerMockTest.java | 13 +++++++------ 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java index 65c485b22d9..975d41a9051 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java @@ -1,5 +1,8 @@ package org.tron.common.logsfilter; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; @@ -26,9 +29,7 @@ import org.tron.protos.Protocol; import org.tron.protos.contract.BalanceContract; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; + public class TransactionLogTriggerCapsuleMockTest { diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java index b9381df8460..ee126049ad0 100644 --- a/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java @@ -1,12 +1,14 @@ package org.tron.common.runtime; +import java.lang.reflect.Method; + import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.tron.core.vm.program.Program; -import java.lang.reflect.Method; + @Slf4j public class RuntimeImplMockTest { diff --git a/framework/src/test/java/org/tron/core/WalletMockTest.java b/framework/src/test/java/org/tron/core/WalletMockTest.java index 9dc0323f8fc..a52da0a95c9 100644 --- a/framework/src/test/java/org/tron/core/WalletMockTest.java +++ b/framework/src/test/java/org/tron/core/WalletMockTest.java @@ -18,6 +18,7 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.LazyStringArrayList; +import com.google.protobuf.ProtocolStringList; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -28,7 +29,6 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import com.google.protobuf.ProtocolStringList; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/framework/src/test/java/org/tron/core/db/ManagerMockTest.java b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java index ff6e0dce3d8..f0e850faf7f 100644 --- a/framework/src/test/java/org/tron/core/db/ManagerMockTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java @@ -68,12 +68,13 @@ public void clearMocks() { public void processTransactionCostTimeMoreThan100() throws Exception { TransactionTrace traceMock = mock(TransactionTrace.class); BandwidthProcessor bandwidthProcessorMock = mock(BandwidthProcessor.class); - try (MockedConstruction mockedConstruction2 = mockConstruction(TransactionTrace.class,(mock, context) -> { - when(mock).thenReturn(traceMock); - }); - MockedConstruction mockedConstruction3 = mockConstruction(BandwidthProcessor.class,(mock, context) -> { - when(mock).thenReturn(bandwidthProcessorMock); - }); + try (MockedConstruction mockedConstruction2 + = mockConstruction(TransactionTrace.class,(mock, context) -> { + when(mock).thenReturn(traceMock); }); + MockedConstruction mockedConstruction3 + = mockConstruction(BandwidthProcessor.class,(mock, context) -> { + when(mock).thenReturn(bandwidthProcessorMock); + }); MockedStatic mockedStatic = mockStatic(TransactionUtil.class)) { Manager dbManager = mock(Manager.class); BalanceContract.TransferContract transferContract = From 42e79c279b7932344c48a60fdfdcda2cb1f4ba2c Mon Sep 17 00:00:00 2001 From: chaozhu Date: Thu, 26 Dec 2024 15:47:42 +0800 Subject: [PATCH 4/4] jacoco.toolVersion optimize --- build.gradle | 3 +++ chainbase/build.gradle | 5 ----- framework/build.gradle | 3 --- plugins/build.gradle | 3 --- 4 files changed, 3 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index c74a31a3c8e..aefae7956ec 100644 --- a/build.gradle +++ b/build.gradle @@ -11,6 +11,9 @@ subprojects { targetCompatibility = JavaVersion.VERSION_1_8 [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' + jacoco { + toolVersion = "0.8.12" // see https://www.jacoco.org/jacoco/trunk/doc/changes.html + } buildscript { repositories { diff --git a/chainbase/build.gradle b/chainbase/build.gradle index 79a246014d7..0fb98629856 100644 --- a/chainbase/build.gradle +++ b/chainbase/build.gradle @@ -2,7 +2,6 @@ description = "chainbase – a decentralized database for blockchain." // Dependency versions // --------------------------------------- -def jacocoVersion = "0.8.0" def jansiVersion = "1.16" // -------------------------------------- @@ -41,10 +40,6 @@ test { } } -jacoco { - toolVersion = jacocoVersion // See http://www.eclemma.org/jacoco/. -} - jacocoTestReport { reports { xml.enabled = true diff --git a/framework/build.gradle b/framework/build.gradle index ec113c93cb1..10477fb71b3 100644 --- a/framework/build.gradle +++ b/framework/build.gradle @@ -15,9 +15,6 @@ def versions = [ checkstyle: '8.7', ] -jacoco { - toolVersion = "0.8.1" -} configurations { diff --git a/plugins/build.gradle b/plugins/build.gradle index 7028686f3d0..03ac6d84150 100644 --- a/plugins/build.gradle +++ b/plugins/build.gradle @@ -5,9 +5,6 @@ plugins { apply plugin: 'application' apply plugin: 'checkstyle' -jacoco { - toolVersion = "0.8.8" -} def versions = [ checkstyle: '8.7', ]