diff --git a/build.gradle b/build.gradle index 8db08f4fe7e..b1aba1c0aa9 100644 --- a/build.gradle +++ b/build.gradle @@ -52,10 +52,7 @@ subprojects { testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' testImplementation group: 'junit', name: 'junit', version: '4.13.2' - testImplementation "org.mockito:mockito-core:3.10.0" - testImplementation group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.9' - testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9' - + testImplementation "org.mockito:mockito-core:2.13.0" } task sourcesJar(type: Jar, dependsOn: classes) { diff --git a/framework/build.gradle b/framework/build.gradle index 4519f93e44d..ec113c93cb1 100644 --- a/framework/build.gradle +++ b/framework/build.gradle @@ -2,14 +2,12 @@ plugins { id "org.gradle.test-retry" version "1.5.9" id "org.sonarqube" version "2.6" id "com.gorylenko.gradle-git-properties" version "2.4.1" - id "io.github.surpsg.offlins" version "0.3.0" } gitProperties.failOnNoGitDirectory = false; apply plugin: 'application' apply plugin: 'checkstyle' -apply plugin: "io.github.surpsg.offlins" mainClassName = 'org.tron.program.FullNode' @@ -18,7 +16,7 @@ def versions = [ ] jacoco { - toolVersion = "0.8.8" + toolVersion = "0.8.1" } @@ -123,12 +121,10 @@ test { testLogging { exceptionFormat = 'full' } - /* jacoco { destinationFile = file("$buildDir/jacoco/jacocoTest.exec") classDumpDir = file("$buildDir/jacoco/classpathdumps") } - */ if (isWindows()) { exclude '**/ShieldedTransferActuatorTest.class' exclude '**/BackupDbUtilTest.class' @@ -145,7 +141,6 @@ test { } } -/* jacocoTestReport { reports { xml.enabled true @@ -154,26 +149,6 @@ jacocoTestReport { } getExecutionData().setFrom(fileTree('../framework/build/jacoco').include("**.exec")) } - */ - -offlinsCoverage { - jacocoVersion = '0.8.8' // Optional. By default `0.8.8` - - reports { - html.enabled.set true // Optional. By default `true` - html.location.set project.file('build/reports/jacoco/test/html') // Optional. By default `build/reports/jacoco/html` - - xml.enabled.set true // Optional. By default `false` - xml.location.set project.file('build/reports/jacoco/test/jacocoTestReport.xml') - // Optional. By default `build/reports/jacoco/coverageReport.xml` - - csv.enabled.set true // Optional. By default `false` - csv.location.set project.file('build/reports/jacoco/test/csvCoverage.csv') - // Optional. By default `build/reports/jacoco/coverageReport.csv` - } -} - - def binaryRelease(taskName, jarName, mainClass) { return tasks.create("${taskName}", Jar) { diff --git a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java deleted file mode 100644 index 8734206d3c5..00000000000 --- a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package org.tron.common.logsfilter; - -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; - -import com.google.protobuf.ByteString; -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.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ - TransactionLogTriggerCapsule.class, - TransactionTrace.class -}) -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() { - Mockito.framework().clearInlineMocks(); - } - - - @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); - - List pojoList = Whitebox.invokeMethod(triggerCapsule, - "getInternalTransactionList", 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 93401e0d415..76dd6e99158 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java @@ -13,16 +13,13 @@ 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; @@ -178,70 +175,4 @@ 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 deleted file mode 100644 index 0b8228f28ba..00000000000 --- a/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.tron.common.runtime; - -import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -import org.tron.core.vm.program.Program; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({RuntimeImpl.class}) -@Slf4j -public class RuntimeImplMockTest { - @After - public void clearMocks() { - Mockito.framework().clearInlineMocks(); - } - - @Test - public void testSetResultCode1() throws Exception { - RuntimeImpl runtime = new RuntimeImpl(); - ProgramResult programResult = new ProgramResult(); - - Program.BadJumpDestinationException badJumpDestinationException - = new Program.BadJumpDestinationException("Operation with pc isn't 'JUMPDEST': PC[%d];", 0); - programResult.setException(badJumpDestinationException); - Whitebox.invokeMethod(runtime,"setResultCode", programResult); - - Program.OutOfTimeException outOfTimeException - = new Program.OutOfTimeException("CPU timeout for 0x0a executing"); - programResult.setException(outOfTimeException); - Whitebox.invokeMethod(runtime,"setResultCode", programResult); - - Program.PrecompiledContractException precompiledContractException - = new Program.PrecompiledContractException("precompiled contract exception"); - programResult.setException(precompiledContractException); - Whitebox.invokeMethod(runtime,"setResultCode", programResult); - - Program.StackTooSmallException stackTooSmallException - = new Program.StackTooSmallException("Expected stack size %d but actual %d;", 100, 10); - programResult.setException(stackTooSmallException); - Whitebox.invokeMethod(runtime,"setResultCode", programResult); - - Program.JVMStackOverFlowException jvmStackOverFlowException - = new Program.JVMStackOverFlowException(); - programResult.setException(jvmStackOverFlowException); - Whitebox.invokeMethod(runtime,"setResultCode", programResult); - - Assert.assertTrue(true); - } - -} - diff --git a/framework/src/test/java/org/tron/core/WalletMockTest.java b/framework/src/test/java/org/tron/core/WalletMockTest.java deleted file mode 100644 index e3b4384ff1b..00000000000 --- a/framework/src/test/java/org/tron/core/WalletMockTest.java +++ /dev/null @@ -1,1174 +0,0 @@ -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.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.whenNew; - -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.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ - Wallet.class, - Args.class, - CommonParameter.class, - TransactionCapsule.class, - com.google.protobuf.Message.class, - ByteUtil.class, - KeyIo.class, - PaymentAddress.class, - Protocol.Transaction.Contract.ContractType.class -}) -public class WalletMockTest { - - @After - public void clearMocks() { - Mockito.framework().clearInlineMocks(); - } - - @Test - public void testSetTransactionNullException() throws Exception { - Wallet wallet = new Wallet(); - TransactionCapsule transactionCapsuleMock - = mock(TransactionCapsule.class); - Whitebox.invokeMethod(wallet, - "setTransaction", 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; - TransactionCapsule transactionCapsuleMock = - mock(TransactionCapsule.class); - - whenNew(TransactionCapsule.class) - .withAnyArguments().thenReturn(transactionCapsuleMock); - try { - Whitebox.invokeMethod(wallet, - "createTransactionCapsuleWithoutValidateWithTimeout", - message, contractType, timeout); - } catch (Exception e) { - assertTrue(false); - } - - 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(); - - TransactionCapsule transactionCapsuleMock = mock(TransactionCapsule.class); - ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); - Whitebox.setInternalState(wallet, "chainBaseManager", chainBaseManagerMock); - - when(chainBaseManagerMock.getHeadBlockId()).thenReturn(blockId); - - whenNew(TransactionCapsule.class) - .withAnyArguments().thenReturn(transactionCapsuleMock); - Whitebox.invokeMethod(wallet, - "createTransactionCapsuleWithoutValidateWithTimeout", - 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "minEffectiveConnection", 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "minEffectiveConnection", 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "dbManager", 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "dbManager", managerMock); - Whitebox.setInternalState(wallet, "trxCacheEnable", 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "dbManager", managerMock); - Whitebox.setInternalState(wallet, "chainBaseManager", chainBaseManagerMock); - Whitebox.setInternalState(wallet, "trxCacheEnable", 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); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "dbManager", managerMock); - Whitebox.setInternalState(wallet, "chainBaseManager", chainBaseManagerMock); - Whitebox.setInternalState(wallet, "trxCacheEnable", 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); - TransactionMessage transactionMessageMock - = mock(TransactionMessage.class); - - when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); - when(managerMock.isTooManyPending()).thenReturn(false); - when(chainBaseManagerMock.getDynamicPropertiesStore()) - .thenReturn(dynamicPropertiesStoreMock); - when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); - whenNew(TransactionMessage.class) - .withAnyArguments().thenReturn(transactionMessageMock); - doThrow(tronException).when(managerMock).pushTransaction(any()); - - Whitebox.setInternalState(wallet, "tronNetDelegate", tronNetDelegateMock); - Whitebox.setInternalState(wallet, "dbManager", managerMock); - Whitebox.setInternalState(wallet, "chainBaseManager", chainBaseManagerMock); - Whitebox.setInternalState(wallet, "trxCacheEnable", false); - } - - @Test - public void testBroadcastTransactionValidateSignatureException() throws Exception { - 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 { - 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 { - 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 { - 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 { - 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 { - 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - Whitebox.setInternalState(wallet, "chainBaseManager", 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(); - - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - - Whitebox.setInternalState(wallet, "chainBaseManager", 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(); - - Whitebox.setInternalState(wallet, "chainBaseManager", 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(); - - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - 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); - 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() { - Wallet wallet = new Wallet(); - byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); - - assertThrows( - ContractExeException.class, - () -> { - wallet.getShieldedContractScalingFactor(contractAddress); - } - ); - } - - @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( - "public amount must be non-negative", - Exception.class, - () -> { - Whitebox.invokeMethod(wallet, "checkBigIntegerRange", - 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()); - - assertThrows( - ContractExeException.class, - () -> { - PowerMockito.when(walletMock, - "checkPublicAmount", - address, fromAmount, toAmount - ).thenCallRealMethod(); - } - ); - } - - @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); - assertThrows( - ContractValidateException.class, - () -> { - PowerMockito.when(walletMock, - "checkPublicAmount", - address, fromAmount, toAmount - ).thenCallRealMethod(); - } - ); - } - - @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")); - mockStatic(ByteUtil.class); - when(ByteUtil.bytesToBigInteger(any())).thenReturn(new BigInteger("-1")); - when(walletMock.getShieldedContractScalingFactor(any())).thenReturn(scalingFactorBytes); - - assertThrows( - ContractValidateException.class, - () -> { - PowerMockito.when(walletMock, - "checkPublicAmount", - address, fromAmount, toAmount - ).thenCallRealMethod(); - } - ); - } - - @Test - public void testGetShieldedTRC20Nullifier() { - 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); - Wallet walletMock = mock(Wallet.class); - mockStatic(KeyIo.class); - when(KeyIo.decodePaymentAddress(any())).thenReturn(null); - - assertThrows( - ZksnarkException.class, - () -> { - PowerMockito.when(walletMock, - "getShieldedTRC20Nullifier", - note, pos, ak, nk - ).thenCallRealMethod(); - } - ); - } - - @Test - public void testGetShieldedTRC20LogType() { - Wallet walletMock = mock(Wallet.class); - Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder().build(); - byte[] contractAddress = "contractAddress".getBytes(StandardCharsets.UTF_8); - LazyStringArrayList topicsList = new LazyStringArrayList(); - assertThrows( - ZksnarkException.class, - () -> { - Whitebox.invokeMethod(walletMock, "getShieldedTRC20LogType", - log, contractAddress, topicsList); - } - ); - } - - @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 { - Whitebox.invokeMethod(wallet, - "getShieldedTRC20LogType", - 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 { - Whitebox.invokeMethod(wallet, - "getShieldedTRC20LogType", - log, - contractAddress, - topicsList); - } catch (Exception e) { - assertTrue(false); - } - assertTrue(true); - } - - @Test - public void testBuildShieldedTRC20InputWithAK() throws ZksnarkException { - 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); - Wallet walletMock = mock(Wallet.class); - mockStatic(KeyIo.class); - when(KeyIo.decodePaymentAddress(any())).thenReturn(null); - - assertThrows( - ZksnarkException.class, - () -> { - PowerMockito.when(walletMock, - "buildShieldedTRC20InputWithAK", - builder, - spendNote, - ak, nk - ).thenCallRealMethod(); - } - ); - } - - @Test - public void testBuildShieldedTRC20InputWithAK1() throws Exception { - 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); - Wallet walletMock = mock(Wallet.class); - mockStatic(KeyIo.class); - when(KeyIo.decodePaymentAddress(any())).thenReturn(paymentAddress); - when(paymentAddress.getD()).thenReturn(diversifierT); - when(paymentAddress.getPkD()).thenReturn("pkd".getBytes()); - - PowerMockito.when(walletMock, - "buildShieldedTRC20InputWithAK", - builder, - spendNote, - ak, nk - ).thenCallRealMethod(); - assertTrue(true); - } - - @Test - public void testBuildShieldedTRC20Input() throws ZksnarkException { - 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); - Wallet walletMock = mock(Wallet.class); - mockStatic(KeyIo.class); - when(KeyIo.decodePaymentAddress(any())).thenReturn(paymentAddress); - when(paymentAddress.getD()).thenReturn(diversifierT); - when(paymentAddress.getPkD()).thenReturn("pkd".getBytes()); - try { - PowerMockito.when(walletMock, - "buildShieldedTRC20Input", - builder, - spendNote, - expandedSpendingKey - ).thenCallRealMethod(); - } catch (Exception e) { - assertTrue(false); - } - } - - @Test - public void testGetContractInfo() { - 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); - Whitebox.setInternalState(wallet, "chainBaseManager", chainBaseManagerMock); - when(chainBaseManagerMock.getAccountStore()).thenReturn(accountStore); - when(accountStore.get(any())).thenReturn(null); - - SmartContractOuterClass.SmartContractDataWrapper smartContractDataWrapper = - wallet.getContractInfo(bytesMessage); - assertNull(smartContractDataWrapper); - } - - @Test - public void testGetContractInfo1() { - 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); - - Whitebox.setInternalState(wallet, "chainBaseManager", 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); - } -} diff --git a/framework/src/test/java/org/tron/core/db/ManagerMockTest.java b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java deleted file mode 100755 index 62ffcc9c43d..00000000000 --- a/framework/src/test/java/org/tron/core/db/ManagerMockTest.java +++ /dev/null @@ -1,384 +0,0 @@ -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.when; -import static org.powermock.api.mockito.PowerMockito.spy; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import java.nio.charset.StandardCharsets; - -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({Manager.class, - CommonParameter.class, - Args.class, - TransactionUtil.class}) -@Slf4j -public class ManagerMockTest { - @After - public void clearMocks() { - Mockito.framework().clearInlineMocks(); - } - - @Test - public void processTransactionCostTimeMoreThan100() throws Exception { - Manager dbManager = spy(new Manager()); - 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); - TransactionTrace traceMock = mock(TransactionTrace.class); - RuntimeImpl runtimeMock = mock(RuntimeImpl.class); - BandwidthProcessor bandwidthProcessorMock = mock(BandwidthProcessor.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(); - - // mock static - PowerMockito.mockStatic(TransactionUtil.class); - - Whitebox.setInternalState(dbManager, "chainBaseManager", chainBaseManagerMock); - - BlockCapsule blockCapMock = Mockito.mock(BlockCapsule.class); - - PowerMockito.when(TransactionUtil - .buildTransactionInfoInstance(trxCapMock, blockCapMock, traceMock)) - .thenReturn(transactionInfoCapsuleMock); - - // this make cost > 100 cond is true - PowerMockito.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); - - doNothing().when(dbManager).validateTapos(trxCapMock); - doNothing().when(dbManager).validateCommon(trxCapMock); - doNothing().when(dbManager).validateDup(trxCapMock); - - // mock construct - PowerMockito.whenNew(RuntimeImpl.class).withAnyArguments().thenReturn(runtimeMock); - PowerMockito.whenNew(TransactionTrace.class).withAnyArguments().thenReturn(traceMock); - PowerMockito.whenNew(BandwidthProcessor.class).withAnyArguments() - .thenReturn(bandwidthProcessorMock); - - 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(); - - 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); - - assertNotNull(dbManager.processTransaction(trxCapMock, blockCapMock)); - } - - private void initMockEnv(Manager dbManager, long headNum, long headTime, - long exitHeight, long exitCount, String blockTime) - throws Exception { - ChainBaseManager chainBaseManagerMock = PowerMockito.mock(ChainBaseManager.class); - Args argsMock = PowerMockito.mock(Args.class); - - PowerMockito.mockStatic(CommonParameter.class); - PowerMockito.mockStatic(Args.class); - PowerMockito.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 * * ?" - - Whitebox.setInternalState(dbManager, - "chainBaseManager", chainBaseManagerMock); - } - - @Test - public void testInitAutoStop() throws Exception { - Manager dbManager = spy(new Manager()); - initMockEnv(dbManager, 100L, 12345L, - 10L, 0L, "0 0 12 * * ?"); - - assertThrows( - "shutDownBlockHeight 10 is less than headNum 100", - Exception.class, - () -> { - Whitebox.invokeMethod(dbManager, "initAutoStop"); - } - ); - } - - @Test - public void testInitAutoStop1() throws Exception { - Manager dbManager = spy(new Manager()); - initMockEnv(dbManager,10L, 12345L, - 100L, 0L, "0 0 12 * * ?"); - - assertThrows( - "shutDownBlockCount 0 is less than 1", - Exception.class, - () -> { - Whitebox.invokeMethod(dbManager, "initAutoStop"); - } - ); - } - - @Test - public void testInitAutoStop2() throws Exception { - Manager dbManager = spy(new Manager()); - initMockEnv(dbManager,10L, 99726143865000L, - 100L, 1L, "0 0 12 * * ?"); - - assertThrows( - "shutDownBlockTime 0 0 12 * * ? is illegal", - Exception.class, - () -> { - Whitebox.invokeMethod(dbManager, "initAutoStop"); - } - ); - } - - @Test - public void testInitAutoStop3() throws Exception { - Manager dbManager = spy(new Manager()); - initMockEnv(dbManager,10L, 12345L, - 100L, 1L, "0 0 12 * * ?"); - - assertThrows( - "shutDownBlockHeight 100 and shutDownBlockCount 1 set both", - Exception.class, - () -> { - Whitebox.invokeMethod(dbManager, "initAutoStop"); - } - ); - } - - @Test - public void testInitAutoStop4() throws Exception { - Manager dbManager = spy(new Manager()); - initMockEnv(dbManager, 10L, 12345L, - 100L, -1L, "0 0 12 * * ?"); - - assertThrows( - "shutDownBlockHeight 100 and shutDownBlockTime 0 0 12 * * ? set both", - Exception.class, - () -> { - Whitebox.invokeMethod(dbManager, "initAutoStop"); - } - ); - } - - @Test - public void testInitAutoStop5() throws Exception { - Manager dbManager = spy(new Manager()); - initMockEnv(dbManager,10L, 12345L, - 0L, 1L, "0 0 12 * * ?"); - - assertThrows( - "shutDownBlockCount 1 and shutDownBlockTime 0 0 12 * * ? set both", - Exception.class, - () -> { - Whitebox.invokeMethod(dbManager, "initAutoStop"); - } - ); - } - - @Test - public void testProcessTransaction() throws Exception { - Manager dbManager = spy(new Manager()); - TransactionCapsule transactionCapsuleMock = null; - BlockCapsule blockCapsuleMock = PowerMockito.mock(BlockCapsule.class); - Whitebox.invokeMethod(dbManager, "processTransaction", - 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 = PowerMockito.mock(BlockCapsule.class); - - assertThrows( - ContractSizeNotEqualToOneException.class, - () -> { - Whitebox.invokeMethod(dbManager, "processTransaction", - trxCap, blockCapsuleMock); - } - ); - } - - @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 = PowerMockito.mock(ChainBaseManager.class); - Whitebox.setInternalState(dbManager, "chainBaseManager", 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 = PowerMockito.mock(ChainBaseManager.class); - Whitebox.setInternalState(dbManager, "chainBaseManager", 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()); - Whitebox.invokeMethod(dbManager, "postSolidityFilter", - 100L, 10L); - assertTrue(true); - } - - @Test - public void testReOrgLogsFilter() throws Exception { - Manager dbManager = spy(new Manager()); - CommonParameter commonParameterMock = PowerMockito.mock(Args.class); - PowerMockito.mockStatic(CommonParameter.class); - ChainBaseManager chainBaseManagerMock = PowerMockito.mock(ChainBaseManager.class); - - PowerMockito.when(CommonParameter.getInstance()).thenReturn(commonParameterMock); - when(commonParameterMock.isJsonRpcHttpFullNodeEnable()).thenReturn(true); - when(chainBaseManagerMock.getDynamicPropertiesStore()) - .thenReturn(mock(DynamicPropertiesStore.class)); - Whitebox.setInternalState(dbManager, "chainBaseManager", chainBaseManagerMock); - doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockById(any()); - - Whitebox.invokeMethod(dbManager, "reOrgLogsFilter"); - assertTrue(true); - } - -} 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 deleted file mode 100644 index 92bf06edd72..00000000000 --- a/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java +++ /dev/null @@ -1,33 +0,0 @@ -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.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({PeerStatusCheckMockTest.class}) -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); - } - -} 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 deleted file mode 100644 index 1b3fc354c95..00000000000 --- a/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java +++ /dev/null @@ -1,266 +0,0 @@ -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 com.google.protobuf.ByteString; -import com.google.protobuf.UnknownFieldSet; - -import java.io.CharArrayReader; -import java.io.IOException; -import java.io.StringWriter; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.reflect.Whitebox; -import org.tron.protos.Protocol; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ - JsonFormat.class, -}) -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 { - String out1 = Whitebox.invokeMethod(JsonFormat.class, - "unsignedToString", 100L); - assertEquals("100", out1); - String out2 = Whitebox.invokeMethod(JsonFormat.class, - "unsignedToString", -100L); - assertNotNull(out2); - - String out3 = Whitebox.invokeMethod(JsonFormat.class, - "unsignedToString", 100); - assertEquals("100", out3); - String out4 = Whitebox.invokeMethod(JsonFormat.class, - "unsignedToString", -100); - assertNotNull(out4); - } - - @Test - public void testToStringBuilderWithNonReadableInput() throws Exception { - String inputString = "Hello, World!"; - Readable input = new CharArrayReader(inputString.toCharArray()); - - StringBuilder out = Whitebox.invokeMethod(JsonFormat.class, - "toStringBuilder", input); - assertEquals(inputString, out.toString()); - } - - - @Test - public void testUnicodeEscaped() throws Exception { - char input1 = 0x09; - String out = Whitebox.invokeMethod(JsonFormat.class, - "unicodeEscaped", input1); - assertNotNull(out); - - char input2 = 0x99; - String out2 = Whitebox.invokeMethod(JsonFormat.class, - "unicodeEscaped", input2); - assertNotNull(out2); - - char input3 = 0x999; - String out3 = Whitebox.invokeMethod(JsonFormat.class, - "unicodeEscaped", input3); - assertNotNull(out3); - - char input4 = 0x1001; - String out4 = Whitebox.invokeMethod(JsonFormat.class, - "unicodeEscaped", input4); - assertNotNull(out4); - } - - @Test - public void testEscapeText() throws Exception { - String input1 = "\b\f\n\r\t\\\"\\b\\f\\n\\r\\t\\\\\"test123"; - String out = Whitebox.invokeMethod(JsonFormat.class, - "escapeText", input1); - assertNotNull(out); - } - - @Test - public void testAppendEscapedUnicode() throws Exception { - char input1 = 0x09; - StringBuilder out1 = new StringBuilder(); - Whitebox.invokeMethod(JsonFormat.class, - "appendEscapedUnicode", out1, input1); - assertNotNull(out1); - - char input2 = 0x99; - StringBuilder out2 = new StringBuilder(); - Whitebox.invokeMethod(JsonFormat.class, - "appendEscapedUnicode", out2, input2); - assertNotNull(out2); - - char input3 = 0x999; - StringBuilder out3 = new StringBuilder(); - Whitebox.invokeMethod(JsonFormat.class, - "appendEscapedUnicode", out3, input3); - assertNotNull(out3); - - char input4 = 0x1001; - StringBuilder out4 = new StringBuilder(); - Whitebox.invokeMethod(JsonFormat.class, - "appendEscapedUnicode", out4, input4); - assertNotNull(out4); - } - - @Test - public void testUnescapeText() throws Exception { - String input = "\\u1234\\b\\f\\n\\r\\t\\\\\"test123";; - String out = Whitebox.invokeMethod(JsonFormat.class, - "unescapeText", input); - assertNotNull(out); - } - - @Test - public void testDigitValue() throws Exception { - char input = '1'; - int out = Whitebox.invokeMethod(JsonFormat.class, - "digitValue", input); - assertEquals(1, out); - - char input1 = 'b'; - int out1 = Whitebox.invokeMethod(JsonFormat.class, - "digitValue", input1); - assertEquals(11, out1); - - char input2 = 'B'; - int out2 = Whitebox.invokeMethod(JsonFormat.class, - "digitValue", input2); - assertEquals(11, out2); - } - - @Test - public void testParseUInt64() throws Exception { - String input = "12312312312"; - long out = Whitebox.invokeMethod(JsonFormat.class, - "parseUInt64", input); - assertEquals(12312312312L, out); - - String input1 = "0x10"; - long out1 = Whitebox.invokeMethod(JsonFormat.class, - "parseUInt64", input1); - assertEquals(16L, out1); - - String input2 = "010"; - long out2 = Whitebox.invokeMethod(JsonFormat.class, - "parseUInt64", input2); - assertEquals(8L, out2); - - String input3 = "-12312312312"; - assertThrows( - NumberFormatException.class, - () -> { - Whitebox.invokeMethod(JsonFormat.class, - "parseUInt64", input3); - } - ); - } - - @Test - public void testParseInteger() { - String input1 = "92233720368547758070"; - assertThrows( - NumberFormatException.class, - () -> { - Whitebox.invokeMethod(JsonFormat.class, "parseInteger", - input1, true, true); - } - ); - String input5 = "92233720368547758070"; - assertThrows( - NumberFormatException.class, - () -> { - Whitebox.invokeMethod(JsonFormat.class, "parseInteger", - input5, false, true); - } - ); - - String input2 = "-92233720368547758"; - assertThrows( - NumberFormatException.class, - () -> { - Whitebox.invokeMethod(JsonFormat.class, "parseInteger", - input2, false, true); - } - ); - - String input3 = "92233720368547758070"; - assertThrows( - NumberFormatException.class, - () -> { - Whitebox.invokeMethod(JsonFormat.class, "parseInteger", - input3, false, false); - } - ); - String input4 = "-92233720368547758070"; - assertThrows( - NumberFormatException.class, - () -> { - Whitebox.invokeMethod(JsonFormat.class, "parseInteger", - input4, true, false); - } - ); - } - -} 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 deleted file mode 100644 index a2b5bcbe342..00000000000 --- a/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java +++ /dev/null @@ -1,250 +0,0 @@ -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.junit.runner.RunWith; -import org.mockito.Mockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -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; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({ - Util.class, -}) -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); - } - -}