github.com/turingchain2020/turingchain@v1.1.21/util/util_test.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package util
     6  
     7  import (
     8  	"errors"
     9  	"sync/atomic"
    10  	"testing"
    11  
    12  	"strings"
    13  
    14  	"github.com/turingchain2020/turingchain/common"
    15  	"github.com/turingchain2020/turingchain/common/address"
    16  	log "github.com/turingchain2020/turingchain/common/log/log15"
    17  	"github.com/turingchain2020/turingchain/queue"
    18  	qmocks "github.com/turingchain2020/turingchain/queue/mocks"
    19  	_ "github.com/turingchain2020/turingchain/system/crypto/secp256k1"
    20  	_ "github.com/turingchain2020/turingchain/system/dapp/coins/types"
    21  	"github.com/turingchain2020/turingchain/types"
    22  	"github.com/stretchr/testify/assert"
    23  	"github.com/stretchr/testify/mock"
    24  )
    25  
    26  func TestMakeStringUpper(t *testing.T) {
    27  	originStr := "abcdefg"
    28  	destStr, err := MakeStringToUpper(originStr, 0, 1)
    29  	assert.NoError(t, err)
    30  	assert.Equal(t, "Abcdefg", destStr)
    31  
    32  	destStr, err = MakeStringToUpper(originStr, 2, 2)
    33  	assert.NoError(t, err)
    34  	assert.Equal(t, "abCDefg", destStr)
    35  
    36  	_, err = MakeStringToUpper(originStr, -1, 2)
    37  	assert.Error(t, err)
    38  }
    39  
    40  func TestMakeStringLower(t *testing.T) {
    41  	originStr := "ABCDEFG"
    42  	destStr, err := MakeStringToLower(originStr, 0, 1)
    43  	assert.NoError(t, err)
    44  	assert.Equal(t, "aBCDEFG", destStr)
    45  
    46  	destStr, err = MakeStringToLower(originStr, 2, 2)
    47  	assert.NoError(t, err)
    48  	assert.Equal(t, "ABcdEFG", destStr)
    49  
    50  	_, err = MakeStringToLower(originStr, -1, 2)
    51  	assert.Error(t, err)
    52  }
    53  
    54  func TestResetDatadir(t *testing.T) {
    55  	cfg, _ := types.InitCfg("../cmd/turingchain/turingchain.toml")
    56  	datadir := ResetDatadir(cfg, "$TEMP/hello")
    57  	assert.Equal(t, datadir+"/datadir", cfg.BlockChain.DbPath)
    58  
    59  	cfg, _ = types.InitCfg("../cmd/turingchain/turingchain.toml")
    60  	datadir = ResetDatadir(cfg, "/TEMP/hello")
    61  	assert.Equal(t, datadir+"/datadir", cfg.BlockChain.DbPath)
    62  
    63  	cfg, _ = types.InitCfg("../cmd/turingchain/turingchain.toml")
    64  	datadir = ResetDatadir(cfg, "~/hello")
    65  	assert.Equal(t, datadir+"/datadir", cfg.BlockChain.DbPath)
    66  }
    67  
    68  func TestHexToPrivkey(t *testing.T) {
    69  	key := HexToPrivkey("4257D8692EF7FE13C68B65D6A52F03933DB2FA5CE8FAF210B5B8B80C721CED01")
    70  	addr := address.PubKeyToAddress(key.PubKey().Bytes()).String()
    71  	assert.Equal(t, addr, "12qyocayNF7Lv6C9qW4avxs2E7U41fKSfv")
    72  }
    73  
    74  func TestGetParaExecName(t *testing.T) {
    75  	s := GetParaExecName("user.p.hello.", "world")
    76  	assert.Equal(t, "user.p.hello.world", s)
    77  	s = GetParaExecName("user.p.hello.", "user.p.2.world")
    78  	assert.Equal(t, "user.p.2.world", s)
    79  }
    80  
    81  func TestUpperLower(t *testing.T) {
    82  	out, err := MakeStringToUpper("hello", 0, 1)
    83  	assert.Nil(t, err)
    84  	assert.Equal(t, "Hello", out)
    85  
    86  	out, err = MakeStringToUpper("Hello", 0, 1)
    87  	assert.Nil(t, err)
    88  	assert.Equal(t, "Hello", out)
    89  
    90  	_, err = MakeStringToUpper("Hello", -1, 1)
    91  	assert.NotNil(t, err)
    92  
    93  	_, err = MakeStringToUpper("Hello", 1, -1)
    94  	assert.NotNil(t, err)
    95  
    96  	out, err = MakeStringToLower("hello", 0, 1)
    97  	assert.Nil(t, err)
    98  	assert.Equal(t, "hello", out)
    99  
   100  	out, err = MakeStringToLower("Hello", 0, 1)
   101  	assert.Nil(t, err)
   102  	assert.Equal(t, "hello", out)
   103  
   104  	_, err = MakeStringToLower("Hello", -1, 1)
   105  	assert.NotNil(t, err)
   106  
   107  	_, err = MakeStringToLower("Hello", 1, -1)
   108  	assert.NotNil(t, err)
   109  }
   110  
   111  func TestGenTx(t *testing.T) {
   112  	cfg := types.NewTuringchainConfig(types.GetDefaultCfgstring())
   113  	txs := GenNoneTxs(cfg, TestPrivkeyList[0], 2)
   114  	assert.Equal(t, 2, len(txs))
   115  	assert.Equal(t, "none", string(txs[0].Execer))
   116  	assert.Equal(t, "none", string(txs[1].Execer))
   117  
   118  	txs = GenCoinsTxs(cfg, TestPrivkeyList[0], 2)
   119  	assert.Equal(t, 2, len(txs))
   120  	assert.Equal(t, "coins", string(txs[0].Execer))
   121  	assert.Equal(t, "coins", string(txs[1].Execer))
   122  
   123  	txs = GenTxsTxHeight(cfg, TestPrivkeyList[0], 2, 10)
   124  	assert.Equal(t, 2, len(txs))
   125  	assert.Equal(t, "coins", string(txs[0].Execer))
   126  	assert.Equal(t, "coins", string(txs[1].Execer))
   127  	assert.Equal(t, types.TxHeightFlag+10, txs[0].Expire)
   128  }
   129  
   130  func TestGenBlock(t *testing.T) {
   131  	cfg := types.NewTuringchainConfig(types.GetDefaultCfgstring())
   132  	block2 := CreateNoneBlock(cfg, TestPrivkeyList[0], 2)
   133  	assert.Equal(t, 2, len(block2.Txs))
   134  
   135  	block2 = CreateCoinsBlock(cfg, TestPrivkeyList[0], 2)
   136  	assert.Equal(t, 2, len(block2.Txs))
   137  
   138  	txs := GenNoneTxs(cfg, TestPrivkeyList[0], 2)
   139  	newblock := CreateNewBlock(cfg, block2, txs)
   140  	assert.Equal(t, newblock.Height, block2.Height+1)
   141  	assert.Equal(t, newblock.ParentHash, block2.Hash(cfg))
   142  }
   143  
   144  func TestDelDupKey(t *testing.T) {
   145  	kvs := []*types.KeyValue{
   146  		{Key: []byte("hello"), Value: []byte("world")},
   147  		{Key: []byte("hello1"), Value: []byte("world")},
   148  		{Key: []byte("hello"), Value: []byte("world2")},
   149  	}
   150  	result := []*types.KeyValue{
   151  		{Key: []byte("hello"), Value: []byte("world2")},
   152  		{Key: []byte("hello1"), Value: []byte("world")},
   153  	}
   154  	kvs = DelDupKey(kvs)
   155  	assert.Equal(t, kvs, result)
   156  
   157  	kvs = []*types.KeyValue{
   158  		{Key: []byte("hello1"), Value: []byte("world")},
   159  		{Key: []byte("hello"), Value: []byte("world")},
   160  		{Key: []byte("hello"), Value: []byte("world2")},
   161  	}
   162  	result = []*types.KeyValue{
   163  		{Key: []byte("hello1"), Value: []byte("world")},
   164  		{Key: []byte("hello"), Value: []byte("world2")},
   165  	}
   166  	kvs = DelDupKey(kvs)
   167  	assert.Equal(t, kvs, result)
   168  }
   169  
   170  func BenchmarkDelDupKey(b *testing.B) {
   171  	var kvs []*types.KeyValue
   172  	for i := 0; i < 1000; i++ {
   173  		key := common.GetRandBytes(20, 40)
   174  		value := common.GetRandBytes(40, 60)
   175  		kvs = append(kvs, &types.KeyValue{Key: key, Value: value})
   176  		if i%10 == 0 {
   177  			kvs = append(kvs, &types.KeyValue{Key: key, Value: value})
   178  		}
   179  	}
   180  	b.ResetTimer()
   181  	for i := 0; i < b.N; i++ {
   182  		testkv := make([]*types.KeyValue, len(kvs))
   183  		copy(testkv, kvs)
   184  		newkvs := DelDupKey(testkv)
   185  		if newkvs[len(newkvs)-1] == nil {
   186  			assert.NotNil(b, newkvs[len(newkvs)-1])
   187  		}
   188  	}
   189  }
   190  
   191  func TestDelDupTx(t *testing.T) {
   192  	cfg := types.NewTuringchainConfig(types.GetDefaultCfgstring())
   193  	txs := GenNoneTxs(cfg, TestPrivkeyList[0], 2)
   194  	assert.Equal(t, 2, len(txs))
   195  	assert.Equal(t, "none", string(txs[0].Execer))
   196  	assert.Equal(t, "none", string(txs[1].Execer))
   197  	result := txs
   198  	txs = append(txs, txs...)
   199  	txcache := make([]*types.TransactionCache, len(txs))
   200  	for i := 0; i < len(txcache); i++ {
   201  		txcache[i] = &types.TransactionCache{Transaction: txs[i]}
   202  	}
   203  
   204  	txcacheresult := make([]*types.TransactionCache, len(result))
   205  	for i := 0; i < len(result); i++ {
   206  		txcacheresult[i] = &types.TransactionCache{Transaction: result[i]}
   207  		txcacheresult[i].Hash()
   208  	}
   209  	txcache = DelDupTx(txcache)
   210  	assert.Equal(t, txcache, txcacheresult)
   211  }
   212  
   213  func TestDB(t *testing.T) {
   214  	dir, db, kvdb := CreateTestDB()
   215  	defer CloseTestDB(dir, db)
   216  	err := kvdb.Set([]byte("a"), []byte("b"))
   217  	assert.Nil(t, err)
   218  	value, err := kvdb.Get([]byte("a"))
   219  	assert.Nil(t, err)
   220  	assert.Equal(t, value, []byte("b"))
   221  }
   222  
   223  func TestMockModule(t *testing.T) {
   224  	q := queue.New("channel")
   225  	client := q.Client()
   226  	memKey := "mempool"
   227  	mem := &MockModule{Key: memKey}
   228  	mem.SetQueueClient(client)
   229  
   230  	msg := client.NewMessage(memKey, types.EventTx, &types.Transaction{})
   231  	client.Send(msg, true)
   232  	resp, err := client.Wait(msg)
   233  	assert.Nil(t, err)
   234  	reply, ok := resp.GetData().(*types.Reply)
   235  	assert.Equal(t, ok, true)
   236  	assert.Equal(t, reply.GetIsOk(), false)
   237  	assert.Equal(t, reply.GetMsg(), []byte("mock mempool module not handle message 1"))
   238  }
   239  
   240  func TestJSONPrint(t *testing.T) {
   241  	JSONPrint(t, &types.Reply{})
   242  }
   243  
   244  type testClient struct {
   245  	qmocks.Client
   246  }
   247  
   248  var gid int64
   249  
   250  func (t *testClient) NewMessage(topic string, ty int64, data interface{}) *queue.Message {
   251  	id := atomic.AddInt64(&gid, 1)
   252  	return queue.NewMessage(id, topic, ty, data)
   253  }
   254  
   255  func (t *testClient) FreeMessage(...*queue.Message) {
   256  }
   257  
   258  func (t *testClient) Wait(in *queue.Message) (*queue.Message, error) {
   259  	switch in.Ty {
   260  	case types.EventTxHashList:
   261  		return &queue.Message{Data: &types.TxHashList{}}, nil
   262  	case types.EventExecTxList:
   263  		return &queue.Message{Data: &types.Receipts{Receipts: []*types.Receipt{{Ty: 2}, {Ty: types.ExecErr}}}}, nil
   264  	case types.EventStoreMemSet:
   265  		return &queue.Message{Data: &types.ReplyHash{}}, nil
   266  	case types.EventStoreRollback:
   267  		return &queue.Message{Data: &types.ReplyHash{}}, nil
   268  	case types.EventStoreCommit:
   269  		return &queue.Message{Data: &types.ReplyHash{}}, nil
   270  	case types.EventCheckBlock:
   271  		return &queue.Message{Data: &types.Reply{IsOk: true}}, nil
   272  	}
   273  
   274  	return &queue.Message{}, nil
   275  }
   276  
   277  func TestExecBlock(t *testing.T) {
   278  	str := types.GetDefaultCfgstring()
   279  	new := strings.Replace(str, "Title=\"local\"", "Title=\"turingchain\"", 1)
   280  	cfg := types.NewTuringchainConfig(new)
   281  	client := &testClient{}
   282  	client.On("Send", mock.Anything, mock.Anything).Return(nil)
   283  	client.On("GetConfig", mock.Anything).Return(cfg)
   284  	var txs []*types.Transaction
   285  	addr, priv := Genaddress()
   286  	tx := CreateCoinsTx(cfg, priv, addr, types.Coin)
   287  	tx.Sign(types.SECP256K1, priv)
   288  	txs = append(txs, tx)
   289  	//EventExecTxList returned 2 txs' receipt
   290  	txs = append(txs, tx)
   291  	_, _, err := ExecBlock(client, nil, &types.Block{Txs: txs}, false, true, false)
   292  	assert.NoError(t, err)
   293  }
   294  
   295  func TestExecBlockUpgrade(t *testing.T) {
   296  	cfg := types.NewTuringchainConfig(types.GetDefaultCfgstring())
   297  	client := &testClient{}
   298  	client.On("Send", mock.Anything, mock.Anything).Return(nil)
   299  	client.On("GetConfig", mock.Anything).Return(cfg)
   300  	var txs []*types.Transaction
   301  	addr, priv := Genaddress()
   302  	tx := CreateCoinsTx(cfg, priv, addr, types.Coin)
   303  	tx.Sign(types.SECP256K1, priv)
   304  	txs = append(txs, tx)
   305  	err := ExecBlockUpgrade(client, nil, &types.Block{Txs: txs}, false)
   306  	assert.NoError(t, err)
   307  }
   308  
   309  func TestExecAndCheckBlock(t *testing.T) {
   310  	cfg := types.NewTuringchainConfig(types.GetDefaultCfgstring())
   311  	client := &testClient{}
   312  	client.On("Send", mock.Anything, mock.Anything).Return(nil)
   313  	client.On("GetConfig", mock.Anything).Return(cfg)
   314  	addr, priv := Genaddress()
   315  	tx := CreateCoinsTx(cfg, priv, addr, types.Coin)
   316  	tx.Sign(types.SECP256K1, priv)
   317  	tx2 := CreateCoinsTx(cfg, priv, addr, 2*types.Coin)
   318  	tx2.Sign(types.SECP256K1, priv)
   319  	var txs []*types.Transaction
   320  	txs = append(txs, tx)
   321  	txs = append(txs, tx2)
   322  	_, err := ExecAndCheckBlock(client, &types.Block{}, txs, []int{types.ExecOk, types.ExecErr})
   323  	assert.NoError(t, err)
   324  }
   325  
   326  func TestCheckBlock(t *testing.T) {
   327  	client := &testClient{}
   328  	client.On("Send", mock.Anything, mock.Anything).Return(nil)
   329  	err := CheckBlock(client, nil)
   330  	assert.NoError(t, err)
   331  }
   332  
   333  func TestExecKVSetRollback(t *testing.T) {
   334  	client := &testClient{}
   335  	client.On("Send", mock.Anything, mock.Anything).Return(nil)
   336  	err := ExecKVSetRollback(client, nil)
   337  	assert.NoError(t, err)
   338  }
   339  
   340  func TestCheckDupTx(t *testing.T) {
   341  	cfg := types.NewTuringchainConfig(types.GetDefaultCfgstring())
   342  	client := &testClient{}
   343  	client.On("Send", mock.Anything, mock.Anything).Return(nil)
   344  	client.On("GetConfig", mock.Anything).Return(cfg)
   345  	var txs []*types.Transaction
   346  	addr, priv := Genaddress()
   347  	tx := CreateCoinsTx(cfg, priv, addr, types.Coin)
   348  	tx.Sign(types.SECP256K1, priv)
   349  	txs = append(txs, tx)
   350  	_, err := CheckDupTx(client, txs, 1)
   351  	assert.NoError(t, err)
   352  }
   353  
   354  func TestReportErrEventToFront(t *testing.T) {
   355  	logger := log.New("test")
   356  	client := &testClient{}
   357  	client.On("SendTimeout", mock.Anything, mock.Anything, mock.Anything).Return(nil)
   358  	client.On("WaitTimeout", mock.Anything, mock.Anything).Return(&queue.Message{}, nil)
   359  	ReportErrEventToFront(logger, client, "from", "to", errors.New("test"))
   360  }