From add119e2f3ac0f8530a4cfb3baea8507954b848b Mon Sep 17 00:00:00 2001 From: "morgan.peng" Date: Wed, 12 Apr 2023 19:59:00 +0800 Subject: [PATCH] feat(test): add unit test Add unit test --- .../tron/core/db/ByteArrayWrapperTest.java | 22 ++++ .../java/org/tron/core/db/ManagerTest.java | 83 +++++++++++++- .../filter/RpcApiAccessInterceptorTest.java | 102 ++++++++++++++++++ .../org/tron/keystore/CredentialsTest.java | 48 +++++++++ .../org/tron/keystore/WalletFileTest.java | 28 +++++ .../org/tron/program/SolidityNodeTest.java | 7 ++ 6 files changed, 289 insertions(+), 1 deletion(-) create mode 100644 framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java create mode 100644 framework/src/test/java/org/tron/keystore/CredentialsTest.java create mode 100644 framework/src/test/java/org/tron/keystore/WalletFileTest.java diff --git a/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java b/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java new file mode 100644 index 00000000000..ef4a60ca1da --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java @@ -0,0 +1,22 @@ +package org.tron.core.db; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.testng.Assert; +import org.tron.common.utils.ByteArray; + +@Slf4j +public class ByteArrayWrapperTest { + + @Test + public void createByteArray() { + ByteArrayWrapper byteArrayWrapper1 = new ByteArrayWrapper(ByteArray.fromHexString("1")); + ByteArrayWrapper byteArrayWrapper2 = new ByteArrayWrapper(ByteArray.fromHexString("2")); + Assert.assertEquals(byteArrayWrapper1.compareTo(byteArrayWrapper2), -1); + Assert.assertFalse(byteArrayWrapper1.equals(byteArrayWrapper2)); + Assert.assertFalse(byteArrayWrapper1.getData().equals(byteArrayWrapper2.getData())); + Assert.assertTrue(byteArrayWrapper1.hashCode() != byteArrayWrapper2.hashCode()); + Assert.assertEquals(byteArrayWrapper1.toString().equals(byteArrayWrapper2.toString()),false); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index bed884cc427..916ea784939 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -12,6 +12,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -20,11 +21,14 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.testng.collections.Sets; import org.tron.common.application.TronApplicationContext; import org.tron.common.crypto.ECKey; +import org.tron.common.runtime.RuntimeImpl; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; import org.tron.common.utils.JsonUtil; +import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; @@ -38,8 +42,12 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.WitnessCapsule; import org.tron.core.config.DefaultConfig; +import org.tron.core.config.Parameter; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; +import org.tron.core.db.accountstate.AccountStateEntity; +import org.tron.core.db.accountstate.TrieService; +import org.tron.core.db.accountstate.storetrie.AccountStateStoreTrie; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadBlockException; import org.tron.core.exception.BadItemException; @@ -67,6 +75,7 @@ import org.tron.core.store.ExchangeStore; import org.tron.core.store.ExchangeV2Store; import org.tron.core.store.IncrementalMerkleTreeStore; +import org.tron.core.store.StoreFactory; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.Transaction; @@ -142,6 +151,17 @@ public void updateRecentTransaction() throws Exception { 0, ByteString.copyFrom(new byte[64])); b.addTransaction(trx); dbManager.updateRecentTransaction(b); + try { + dbManager.consumeBandwidth(trx, new TransactionTrace(trx, StoreFactory.getInstance(), + new RuntimeImpl())); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + } + dbManager.consumeMemoFee(trx, new TransactionTrace(trx, StoreFactory.getInstance(), + new RuntimeImpl())); + Assert.assertTrue(dbManager.getTxListFromPending().isEmpty()); + Assert.assertNull(dbManager.getTxFromPending(trx.getTransactionId().toString())); + Assert.assertEquals(0, dbManager.getPendingSize()); Assert.assertEquals(1, chainManager.getRecentTransactionStore().size()); byte[] key = ByteArray.subArray(ByteArray.fromLong(1), 6, 8); byte[] value = chainManager.getRecentTransactionStore().get(key).getData(); @@ -212,6 +232,9 @@ public void pushBlock() { } catch (Exception e) { Assert.assertTrue("pushBlock is error", false); } + TrieService trieService = context.getBean(TrieService.class); + Assert.assertTrue(trieService.getFullAccountStateRootHash().length > 0); + Assert.assertTrue(trieService.getSolidityAccountStateRootHash().length > 0); if (isUnlinked) { Assert.assertEquals("getBlockIdByNum is error", @@ -233,10 +256,50 @@ public void pushBlock() { } catch (ItemNotFoundException e) { Assert.assertTrue(true); } - + try { + dbManager.getBlockChainHashesOnFork(blockCapsule2.getBlockId()); + } catch (Exception e) { + Assert.assertTrue(e instanceof NonCommonBlockException); + } Assert.assertTrue("hasBlocks is error", chainManager.hasBlocks()); } + @Test + public void transactionTest() { + TransactionCapsule trans0 = new TransactionCapsule(Transaction.newBuilder() + .setRawData(Transaction.raw.newBuilder().setData(ByteString.copyFrom( + new byte[Parameter.ChainConstant.BLOCK_SIZE + Constant.ONE_THOUSAND]))).build(), + ContractType.ShieldedTransferContract); + ShieldContract.ShieldedTransferContract trx1 = ShieldContract.ShieldedTransferContract + .newBuilder() + .setFromAmount(10) + .setToAmount(10) + .build(); + TransactionCapsule trans = new TransactionCapsule(trx1, ContractType.ShieldedTransferContract); + try { + dbManager.pushTransaction(trans0); + dbManager.pushTransaction(trans); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + dbManager.rePush(trans0); + ReflectUtils.invokeMethod(dbManager,"filterOwnerAddress", + new Class[]{trans.getClass(), Set.class},trans, Sets.newHashSet()); + Assert.assertNotNull(dbManager.getTxListFromPending()); + + try { + dbManager.validateTapos(trans); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + try { + dbManager.pushVerifiedBlock(chainManager.getHead()); + dbManager.getBlockChainHashesOnFork(chainManager.getHeadBlockId()); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + } + @Test public void GetterInstanceTest() { @@ -260,6 +323,24 @@ public void GetterInstanceTest() { } + @Test + public void entityTest() { + AccountStateStoreTrie trie = context.getBean(AccountStateStoreTrie.class); + Assert.assertNull(trie.getAccount("".getBytes())); + Assert.assertNull(trie.getAccount("".getBytes(), "".getBytes())); + Assert.assertNull(trie.getSolidityAccount("".getBytes())); + Assert.assertTrue(trie.isEmpty()); + AccountStateEntity entity = new AccountStateEntity(); + AccountStateEntity parsedEntity = AccountStateEntity.parse("".getBytes()); + Assert.assertTrue(parsedEntity != null); + Assert.assertTrue(parsedEntity.getAccount() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.Account.of() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.AssetIssue.of() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.Block.of() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.Transaction.of() != null); + + } + @Test public void getHeadTest() { try { diff --git a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java index dd6bd132f0e..edd15fc19de 100644 --- a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java @@ -3,10 +3,12 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; +import io.grpc.stub.ServerCallStreamObserver; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; import org.junit.Assert; @@ -119,6 +121,106 @@ public void testAccessDisabledFullNode() { blockingStubFull.getBlockByNum(message); } + @Test + public void testRpcApiService() { + RpcApiService rpcApiService = context.getBean(RpcApiService.class); + ServerCallStreamObserverTest serverCallStreamObserverTest = new ServerCallStreamObserverTest(); + rpcApiService.getBlockCommon(GrpcAPI.BlockReq.getDefaultInstance(), + serverCallStreamObserverTest); + Assert.assertTrue("Get block Common failed!", serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getBrokerageInfoCommon(GrpcAPI.BytesMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get brokerage info Common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getBurnTrxCommon(GrpcAPI.EmptyMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get burn trx common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getPendingSizeCommon(GrpcAPI.EmptyMessage.getDefaultInstance(), + serverCallStreamObserverTest); + Assert.assertTrue("Get pending size common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getRewardInfoCommon(GrpcAPI.BytesMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get reward info common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionCountByBlockNumCommon( + GrpcAPI.NumberMessage.newBuilder().getDefaultInstanceForType(), + serverCallStreamObserverTest); + Assert.assertTrue("Get transaction count by block num failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionFromPendingCommon(GrpcAPI.BytesMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get transaction from pending failed!", + serverCallStreamObserverTest.isReady() == false); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionListFromPendingCommon(GrpcAPI.EmptyMessage.newBuilder() + .getDefaultInstanceForType(), serverCallStreamObserverTest); + Assert.assertTrue("Get transaction list from pending failed!", + serverCallStreamObserverTest.isReady()); + } + + + class ServerCallStreamObserverTest extends ServerCallStreamObserver { + + Object ret; + + @Override + public boolean isCancelled() { + ret = null; + return true; + } + + @Override + public void setOnCancelHandler(Runnable onCancelHandler) { + } + + @Override + public void setCompression(String compression) { + } + + @Override + public boolean isReady() { + return Objects.nonNull(ret); + } + + @Override + public void setOnReadyHandler(Runnable onReadyHandler) { + } + + @Override + public void disableAutoInboundFlowControl() { + } + + @Override + public void request(int count) { + } + + @Override + public void setMessageCompression(boolean enable) { + } + + @Override + public void onNext(Object value) { + ret = value; + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onCompleted() { + } + } + + @Test public void testAccessDisabledSolidityNode() { List disabledApiList = new ArrayList<>(); diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java new file mode 100644 index 00000000000..3fe2ce02b63 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -0,0 +1,48 @@ +package org.tron.keystore; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import junit.framework.TestCase; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.springframework.util.Assert; +import org.tron.common.crypto.SignUtils; +import org.tron.common.crypto.sm2.SM2; +import org.tron.common.utils.ByteUtil; + +@Slf4j +public class CredentialsTest extends TestCase { + + @Test + public void testCreate() throws NoSuchAlgorithmException { + Credentials credentials = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.hasText(credentials.getAddress(),"Credentials address create failed!"); + Assert.notNull(credentials.getSignInterface(), + "Credentials cryptoEngine create failed"); + } + + @Test + public void testCreateFromSM2() { + try { + Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffffffffff"))); + } catch (Exception e) { + Assert.isInstanceOf(IllegalArgumentException.class, e); + } + } + + @Test + public void testEquals() throws NoSuchAlgorithmException { + Credentials credentials1 = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Credentials credentials2 = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.isTrue(!credentials1.equals(credentials2), + "Credentials instance should be not equal!"); + Assert.isTrue(!(credentials1.hashCode() == credentials2.hashCode()), + "Credentials instance hashcode should be not equal!"); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/keystore/WalletFileTest.java b/framework/src/test/java/org/tron/keystore/WalletFileTest.java new file mode 100644 index 00000000000..7d584b3d8e2 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/WalletFileTest.java @@ -0,0 +1,28 @@ +package org.tron.keystore; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import junit.framework.TestCase; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.crypto.SignUtils; +import org.tron.core.exception.CipherException; + +@Slf4j +public class WalletFileTest extends TestCase { + + + @Test + public void testGetAddress() throws NoSuchAlgorithmException, CipherException { + WalletFile walletFile1 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + WalletFile walletFile2 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.assertTrue(!walletFile1.getAddress().equals(walletFile2.getAddress())); + Assert.assertTrue(!walletFile1.getCrypto().equals(walletFile2.getCrypto())); + Assert.assertTrue(!walletFile1.getId().equals(walletFile2.getId())); + Assert.assertTrue(walletFile1.getVersion() == walletFile2.getVersion()); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 99d6a75adbe..422ec5e6876 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -89,6 +89,13 @@ public void testSolidityGrpcCall() { Block genesisBlock = databaseGrpcClient.getBlock(0); Assert.assertNotNull(genesisBlock); Assert.assertFalse(genesisBlock.getTransactionsList().isEmpty()); + Block invalidBlock = databaseGrpcClient.getBlock(-1); + Assert.assertNotNull(invalidBlock); + try { + databaseGrpcClient = new DatabaseGrpcClient(address, -1); + } catch (Exception e) { + logger.error("Failed to create database grpc client {}", address); + } databaseGrpcClient.shutdown(); }