Commit 67e24195 authored by kingwang's avatar kingwang Committed by 33cn

update chain33

parent 5fdec140
...@@ -555,6 +555,33 @@ func TestGetExecBalance2(t *testing.T) { ...@@ -555,6 +555,33 @@ func TestGetExecBalance2(t *testing.T) {
*/ */
} }
func TestGetBalance(t *testing.T) {
accCoin := NewCoinsAccount()
addr := "1JmFaA6unrCFYEWPGRi7uuXY1KthTJxJEP"
fmt.Println("-------------TestGetExecBalance2---test case1---")
api := new(mocks.QueueProtocolAPI)
in := &types.ReqBalance{}
in.Addresses = append(in.Addresses, addr)
api.On("StoreList", mock.Anything).Return(&types.StoreListReply{}, nil)
api.On("GetLastHeader", mock.Anything).Return(&types.Header{StateHash: []byte("111111111111111111111")}, nil)
api.On("StoreGet", mock.Anything).Return(&types.StoreReplyValue{Values: make([][]byte, 1)}, nil)
_, err := accCoin.GetBalance(api, in)
assert.Nil(t, err)
fmt.Println("-------------TestGetExecBalance2---test case2---")
in.StateHash = "111111111111111111111"
_, err = accCoin.GetBalance(api, in)
assert.Nil(t, err)
fmt.Println("-------------TestGetExecBalance2---test case3---")
in.Execer = "coins"
//api.On("StoreList", mock.Anything).Return(nil, types.ErrInvalidParam)
_, err = accCoin.GetBalance(api, in)
t.Log(err)
assert.Nil(t, err)
}
func TestDB_Mint(t *testing.T) { func TestDB_Mint(t *testing.T) {
_, tokenCoin := GenerAccDb() _, tokenCoin := GenerAccDb()
tokenCoin.GenerAccData() tokenCoin.GenerAccData()
......
...@@ -12,10 +12,9 @@ import ( ...@@ -12,10 +12,9 @@ import (
"time" "time"
"github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/common/crypto"
_ "github.com/33cn/chain33/system/crypto/init"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
_ "github.com/33cn/chain33/system/crypto/init"
) )
func genkey() crypto.PrivKey { func genkey() crypto.PrivKey {
...@@ -105,3 +104,8 @@ func BenchmarkExecAddress(b *testing.B) { ...@@ -105,3 +104,8 @@ func BenchmarkExecAddress(b *testing.B) {
duration = end - start duration = end - start
fmt.Println("duration without cache:", strconv.FormatInt(duration, 10)) fmt.Println("duration without cache:", strconv.FormatInt(duration, 10))
} }
func TestExecPubKey(t *testing.T) {
pubkey := ExecPubKey("test")
assert.True(t, len(pubkey) == 32)
}
...@@ -13,11 +13,37 @@ import ( ...@@ -13,11 +13,37 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func TestGet(t *testing.T) {
require := require.New(t)
name := crypto.GetName(1)
require.Equal("secp256k1", name)
name = crypto.GetName(2)
require.Equal("ed25519", name)
name = crypto.GetName(3)
require.Equal("sm2", name)
ty := crypto.GetType("secp256k1")
require.True(ty == 1)
ty = crypto.GetType("ed25519")
require.True(ty == 2)
ty = crypto.GetType("sm2")
require.True(ty == 3)
}
func TestRipemd160(t *testing.T) {
require := require.New(t)
b := crypto.Ripemd160([]byte("test"))
require.NotNil(b)
}
func TestAll(t *testing.T) { func TestAll(t *testing.T) {
testCrypto(t, "ed25519") testCrypto(t, "ed25519")
testFromBytes(t, "ed25519") testFromBytes(t, "ed25519")
testCrypto(t, "secp256k1") testCrypto(t, "secp256k1")
testFromBytes(t, "secp256k1") testFromBytes(t, "secp256k1")
testCrypto(t, "sm2")
testFromBytes(t, "sm2")
} }
func testFromBytes(t *testing.T, name string) { func testFromBytes(t *testing.T, name string) {
......
...@@ -24,6 +24,8 @@ import ( ...@@ -24,6 +24,8 @@ import (
"os" "os"
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
const ( const (
...@@ -341,3 +343,23 @@ func Example_mac() { ...@@ -341,3 +343,23 @@ func Example_mac() {
fmt.Printf("%x\n", h) fmt.Printf("%x\n", h)
// ProtoToJson: 78de2974bd2711d5549ffd32b753ef0f5fa80a0db2556db60f0987eb8a9218ff // ProtoToJson: 78de2974bd2711d5549ffd32b753ef0f5fa80a0db2556db60f0987eb8a9218ff
} }
func TestNew(t *testing.T) {
d28 := Sum224(nil)
assert.True(t, len(d28) == 28)
d32 := Sum256(nil)
assert.True(t, len(d32) == 32)
d48 := Sum384(nil)
assert.True(t, len(d48) == 48)
d64 := Sum512(nil)
assert.True(t, len(d64) == 64)
d32 = KeccakSum256(nil)
assert.True(t, len(d32) == 32)
d32 = KeccakSum512(nil)
assert.True(t, len(d32) == 32)
}
...@@ -75,5 +75,6 @@ func TestWalk(t *testing.T) { ...@@ -75,5 +75,6 @@ func TestWalk(t *testing.T) {
assert.Equal(t, "222", iter.First().Value.(string)) assert.Equal(t, "222", iter.First().Value.(string))
assert.Equal(t, int64(1), iter.Last().Score) assert.Equal(t, int64(1), iter.Last().Score)
assert.Equal(t, "111", iter.Last().Value.(string)) assert.Equal(t, "111", iter.Last().Value.(string))
l.Print()
} }
...@@ -32,6 +32,11 @@ func testDBGet(t *testing.T, db dbm.KV) { ...@@ -32,6 +32,11 @@ func testDBGet(t *testing.T, db dbm.KV) {
v, err = db.Get([]byte("k1")) v, err = db.Get([]byte("k1"))
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, v, []byte("v11")) assert.Equal(t, v, []byte("v11"))
stateDb := db.(*StateDB)
vs, err := stateDb.BatchGet([][]byte{[]byte("k1")})
assert.NoError(t, err)
assert.Equal(t, [][]byte{[]byte("v11")}, vs)
} }
func TestStateDBTxGetOld(t *testing.T) { func TestStateDBTxGetOld(t *testing.T) {
......
package executor
import (
"testing"
"time"
"github.com/33cn/chain33/types"
"github.com/33cn/chain33/util"
"github.com/stretchr/testify/assert"
)
func TestPlugin(t *testing.T) {
dir, ldb, kvdb := util.CreateTestDB()
defer util.CloseTestDB(dir, ldb)
ctx := &executorCtx{
stateHash: nil,
height: 1,
blocktime: time.Now().Unix(),
difficulty: 1,
mainHash: nil,
parentHash: nil,
}
var txs []*types.Transaction
addr, priv := util.Genaddress()
tx := util.CreateCoinsTx(priv, addr, types.Coin)
tx.Sign(types.SECP256K1, priv)
txs = append(txs, tx)
for _, plugin := range globalPlugins {
detail := &types.BlockDetail{
Block: &types.Block{Txs: txs},
Receipts: []*types.ReceiptData{{}},
}
executor := newExecutor(ctx, &Executor{}, kvdb, txs, nil)
_, _, err := plugin.CheckEnable(executor, false)
assert.NoError(t, err)
kvs, err := plugin.ExecLocal(executor, detail)
assert.NoError(t, err)
for _, kv := range kvs {
err = kvdb.Set(kv.Key, kv.Value)
assert.NoError(t, err)
}
_, err = plugin.ExecDelLocal(executor, detail)
assert.NoError(t, err)
}
}
func TestPluginBase(t *testing.T) {
base := new(pluginBase)
dir, ldb, kvdb := util.CreateTestDB()
defer util.CloseTestDB(dir, ldb)
ctx := &executorCtx{
stateHash: nil,
height: 0,
blocktime: time.Now().Unix(),
difficulty: 1,
mainHash: nil,
parentHash: nil,
}
executor := newExecutor(ctx, &Executor{}, kvdb, nil, nil)
_, _, err := base.checkFlag(executor, nil, true)
assert.NoError(t, err)
k := []byte("test")
v := types.Encode(&types.Int64{})
err = kvdb.Set(k, v)
assert.NoError(t, err)
_, _, err = base.checkFlag(executor, k, true)
assert.NoError(t, err)
}
...@@ -177,7 +177,7 @@ func (client *client) Close() { ...@@ -177,7 +177,7 @@ func (client *client) Close() {
atomic.StoreInt32(&client.isClosed, 1) atomic.StoreInt32(&client.isClosed, 1)
close(client.Recv()) close(client.Recv())
for msg := range client.Recv() { for msg := range client.Recv() {
msg.ReplyErr("client.close", types.ErrChannelClosed) msg.Reply(client.NewMessage(msg.Topic, msg.Ty, types.ErrChannelClosed))
} }
} }
......
...@@ -10,6 +10,7 @@ import ( ...@@ -10,6 +10,7 @@ import (
"time" "time"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert"
) )
func init() { func init() {
...@@ -187,11 +188,17 @@ func TestClientClose(t *testing.T) { ...@@ -187,11 +188,17 @@ func TestClientClose(t *testing.T) {
}() }()
msg := client.NewMessage("mempool", types.EventTx, "hello") msg := client.NewMessage("mempool", types.EventTx, "hello")
err := client.Send(msg, true) err := client.Send(msg, true)
if err == types.ErrChannelClosed {
return
}
if err != nil { //chan is closed if err != nil { //chan is closed
t.Error(err) t.Error(err)
return return
} }
_, err = client.Wait(msg) _, err = client.Wait(msg)
if err == types.ErrChannelClosed {
return
}
if err != nil { if err != nil {
t.Error(err) t.Error(err)
return return
...@@ -213,6 +220,44 @@ func TestPrintMessage(t *testing.T) { ...@@ -213,6 +220,44 @@ func TestPrintMessage(t *testing.T) {
t.Log(msg) t.Log(msg)
} }
func TestMessage_ReplyErr(t *testing.T) {
q := New("channel")
assert.Equal(t, "channel", q.Name())
//接收消息
go func() {
client := q.Client()
client.Sub("mempool")
for msg := range client.Recv() {
if msg.Data == nil {
msg.ReplyErr("test", fmt.Errorf("test error"))
break
}
msg.Reply(NewMessage(0, "mempool", types.EventReply, types.Reply{IsOk: true, Msg: []byte("test ok")}))
}
}()
//发送消息
go func() {
client := q.Client()
msg := client.NewMessage("mempool", types.EventTx, "hello")
err := client.Send(msg, true)
if err != nil { //chan is closed
t.Error(err)
return
}
msg = client.NewMessage("mempool", types.EventTx, nil)
err = client.Send(msg, true)
if err != nil {
t.Error(err)
return
}
client.CloseQueue()
}()
q.Start()
}
func TestChanSubCallback(t *testing.T) { func TestChanSubCallback(t *testing.T) {
q := New("channel") q := New("channel")
client := q.Client() client := q.Client()
...@@ -465,6 +510,9 @@ func TestChannelClose(t *testing.T) { ...@@ -465,6 +510,9 @@ func TestChannelClose(t *testing.T) {
return return
} }
_, err = client.Wait(msg) _, err = client.Wait(msg)
if err == types.ErrChannelClosed {
return
}
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
......
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
package rpc package rpc
import ( import (
"testing" "encoding/hex"
"fmt" "fmt"
"testing"
"github.com/33cn/chain33/account" "github.com/33cn/chain33/account"
"github.com/33cn/chain33/client/mocks" "github.com/33cn/chain33/client/mocks"
...@@ -67,6 +67,12 @@ func testCreateRawTransactionTo(t *testing.T) { ...@@ -67,6 +67,12 @@ func testCreateRawTransactionTo(t *testing.T) {
client := newTestChannelClient() client := newTestChannelClient()
rawtx, err := client.CreateRawTransaction(&tx) rawtx, err := client.CreateRawTransaction(&tx)
assert.NoError(t, err)
reqDecode := &types.ReqDecodeRawTransaction{TxHex: hex.EncodeToString(rawtx)}
_, err = client.DecodeRawTransaction(reqDecode)
assert.NoError(t, err)
assert.Nil(t, err) assert.Nil(t, err)
var mytx types.Transaction var mytx types.Transaction
err = types.Decode(rawtx, &mytx) err = types.Decode(rawtx, &mytx)
...@@ -343,21 +349,30 @@ func TestChannelClient_GetBalance(t *testing.T) { ...@@ -343,21 +349,30 @@ func TestChannelClient_GetBalance(t *testing.T) {
testChannelClient_GetBalanceOther(t) testChannelClient_GetBalanceOther(t)
} }
// func TestChannelClient_GetTotalCoins(t *testing.T) { func TestChannelClient_GetTotalCoins(t *testing.T) {
// client := newTestChannelClient() client := new(channelClient)
// data, err := client.GetTotalCoins(nil) api := new(mocks.QueueProtocolAPI)
// assert.NotNil(t, err) client.Init(&qmock.Client{}, api)
// assert.Nil(t, data) api.On("StoreGetTotalCoins", mock.Anything).Return(&types.ReplyGetTotalCoins{}, nil)
// _, err := client.GetTotalCoins(&types.ReqGetTotalCoins{})
// // accountdb = assert.NoError(t, err)
// token := &types.ReqGetTotalCoins{
// Symbol: "CNY", // accountdb =
// StateHash: []byte("1234"), //token := &types.ReqGetTotalCoins{
// StartKey: []byte("sad"), // Symbol: "CNY",
// Count: 1, // StateHash: []byte("1234"),
// Execer: "coin", // StartKey: []byte("sad"),
// } // Count: 1,
// data, err = client.GetTotalCoins(token) // Execer: "coin",
// assert.NotNil(t, data) //}
// assert.Nil(t, err) //data, err = client.GetTotalCoins(token)
// } //assert.NotNil(t, data)
//assert.Nil(t, err)
}
func TestChannelClient_CreateNoBalanceTransaction(t *testing.T) {
client := new(channelClient)
in := &types.NoBalanceTx{}
_, err := client.CreateNoBalanceTransaction(in)
assert.NoError(t, err)
}
...@@ -1069,3 +1069,99 @@ func TestReWriteRawTx(t *testing.T) { ...@@ -1069,3 +1069,99 @@ func TestReWriteRawTx(t *testing.T) {
assert.Equal(t, int64(130000000000), tx.Expire) assert.Equal(t, int64(130000000000), tx.Expire)
assert.Equal(t, in.To, tx.To) assert.Equal(t, in.To, tx.To)
} }
func TestGrpc_CreateNoBalanceTransaction(t *testing.T) {
_, err := g.CreateNoBalanceTransaction(getOkCtx(), &pb.NoBalanceTx{})
assert.NoError(t, err)
}
func TestGrpc_CreateRawTransaction(t *testing.T) {
_, err := g.CreateRawTransaction(getOkCtx(), &pb.CreateTx{})
assert.NoError(t, err)
}
func TestGrpc_CreateTransaction(t *testing.T) {
_, err := g.CreateTransaction(getOkCtx(), &pb.CreateTxIn{Execer: []byte("coins")})
assert.Equal(t, err, types.ErrActionNotSupport)
}
func TestGrpc_CreateRawTxGroup(t *testing.T) {
_, err := g.CreateRawTxGroup(getOkCtx(), &pb.CreateTransactionGroup{})
assert.Equal(t, types.ErrTxGroupCountLessThanTwo, err)
}
func TestGrpc_SendRawTransaction(t *testing.T) {
transfer := &types.Transaction{
Execer: []byte(types.ExecName("ticket")),
}
payload := types.Encode(transfer)
qapi.On("SendTx", mock.Anything).Return(nil, nil)
var param = &types.SignedTx{
Unsign: payload,
Sign: []byte("123"),
Pubkey: []byte("123"),
Ty: 1,
}
_, err := g.SendRawTransaction(getOkCtx(), param)
assert.NoError(t, err)
}
func TestGrpc_GetAddrOverview(t *testing.T) {
_, err := g.GetAddrOverview(getOkCtx(), &types.ReqAddr{})
assert.Equal(t, err, types.ErrInvalidAddress)
}
func TestGrpc_GetBalance(t *testing.T) {
qapi.On("StoreGet", mock.Anything).Return(nil, types.ErrInvalidParam)
_, err := g.GetBalance(getOkCtx(), &types.ReqBalance{})
assert.Equal(t, err, types.ErrInvalidParam)
}
func TestGrpc_GetAllExecBalance(t *testing.T) {
_, err := g.GetAllExecBalance(getOkCtx(), &pb.ReqAllExecBalance{})
assert.Equal(t, err, types.ErrInvalidAddress)
}
func TestGrpc_QueryConsensus(t *testing.T) {
qapi.On("QueryConsensus", mock.Anything).Return(&types.ReqString{Data: "test"}, nil)
_, err := g.QueryConsensus(getOkCtx(), &pb.ChainExecutor{})
assert.NoError(t, err)
}
func TestGrpc_ExecWallet(t *testing.T) {
qapi.On("ExecWallet", mock.Anything).Return(&types.ReqString{Data: "test"}, nil)
_, err := g.ExecWallet(getOkCtx(), &pb.ChainExecutor{})
assert.NoError(t, err)
}
func TestGrpc_GetLastBlockSequence(t *testing.T) {
qapi.On("GetLastBlockSequence", mock.Anything).Return(nil, nil)
_, err := g.GetLastBlockSequence(getOkCtx(), &types.ReqNil{})
assert.NoError(t, err)
}
func TestGrpc_GetBlockByHashes(t *testing.T) {
qapi.On("GetBlockByHashes", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
_, err := g.GetBlockByHashes(getOkCtx(), &types.ReqHashes{})
assert.NoError(t, err)
}
func TestGrpc_GetSequenceByHash(t *testing.T) {
qapi.On("GetSequenceByHash", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
_, err := g.GetSequenceByHash(getOkCtx(), &pb.ReqHash{})
assert.NoError(t, err)
}
func TestGrpc_SignRawTx(t *testing.T) {
qapi.On("SignRawTx", mock.Anything, mock.Anything, mock.Anything).Return(nil, nil)
_, err := g.SignRawTx(getOkCtx(), &types.ReqSignRawTx{})
assert.NoError(t, err)
}
func TestGrpc_QueryRandNum(t *testing.T) {
qapi.On("Query", mock.Anything, mock.Anything, mock.Anything).Return(&pb.ReplyHash{Hash: []byte("test")}, nil)
_, err := g.QueryRandNum(getOkCtx(), &pb.ReqRandHash{})
assert.NoError(t, err)
}
...@@ -661,28 +661,27 @@ func TestChain33_QueryTransactionOk(t *testing.T) { ...@@ -661,28 +661,27 @@ func TestChain33_QueryTransactionOk(t *testing.T) {
func TestChain33_GetBlocks(t *testing.T) { func TestChain33_GetBlocks(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
api.On("GetBlocks", &types.ReqBlocks{Pid: []string{""}}).Return(nil, errors.New("error value")) api.On("GetBlocks", &types.ReqBlocks{Pid: []string{""}}).Return(&types.BlockDetails{Items: []*types.BlockDetail{{}}}, nil)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
var testResult interface{} var testResult interface{}
data := rpctypes.BlockParam{} data := rpctypes.BlockParam{}
err := testChain33.GetBlocks(data, &testResult) err := testChain33.GetBlocks(data, &testResult)
t.Log(err) t.Log(err)
assert.Equal(t, nil, testResult) assert.NoError(t, err)
assert.NotNil(t, err)
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
func TestChain33_GetLastHeader(t *testing.T) { func TestChain33_GetLastHeader(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
api.On("GetBlocks", &types.ReqBlocks{Pid: []string{""}}).Return(nil, errors.New("error value")) api.On("GetLastHeader", mock.Anything).Return(&types.Header{}, nil)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
var testResult interface{} var testResult interface{}
data := rpctypes.BlockParam{} data := &types.ReqNil{}
err := testChain33.GetBlocks(data, &testResult) err := testChain33.GetLastHeader(data, &testResult)
t.Log(err) t.Log(err)
assert.Equal(t, nil, testResult) assert.NotNil(t, &testResult)
assert.NotNil(t, err) assert.NoError(t, err)
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
...@@ -691,13 +690,13 @@ func TestChain33_GetTxByAddr(t *testing.T) { ...@@ -691,13 +690,13 @@ func TestChain33_GetTxByAddr(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
api.On("GetTransactionByAddr", &types.ReqAddr{}).Return(nil, errors.New("error value")) api.On("GetTransactionByAddr", mock.Anything).Return(&types.ReplyTxInfos{TxInfos: []*types.ReplyTxInfo{{}}}, nil)
var testResult interface{} var testResult interface{}
data := types.ReqAddr{} data := types.ReqAddr{}
err := testChain33.GetTxByAddr(data, &testResult) err := testChain33.GetTxByAddr(data, &testResult)
t.Log(err) t.Log(err)
assert.Equal(t, nil, testResult) assert.NotNil(t, testResult)
assert.NotNil(t, err) assert.NoError(t, err)
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
...@@ -706,15 +705,14 @@ func TestChain33_GetTxByHashes(t *testing.T) { ...@@ -706,15 +705,14 @@ func TestChain33_GetTxByHashes(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
var parm types.ReqHashes api.On("GetTransactionByHash", mock.Anything).Return(&types.TransactionDetails{}, nil)
parm.Hashes = make([][]byte, 0)
api.On("GetTransactionByHash", &parm).Return(nil, errors.New("error value"))
var testResult interface{} var testResult interface{}
data := rpctypes.ReqHashes{} data := rpctypes.ReqHashes{}
data.Hashes = append(data.Hashes, "0xdcf13a93e3bf58534c773e13d339894c18dafbd3ff273a9d1caa0c2bec8e8cd6")
err := testChain33.GetTxByHashes(data, &testResult) err := testChain33.GetTxByHashes(data, &testResult)
t.Log(err) t.Log(err)
assert.Equal(t, nil, testResult) assert.NotNil(t, testResult)
assert.NotNil(t, err) assert.NoError(t, err)
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
...@@ -723,17 +721,29 @@ func TestChain33_GetMempool(t *testing.T) { ...@@ -723,17 +721,29 @@ func TestChain33_GetMempool(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
api.On("GetMempool").Return(nil, errors.New("error value")) api.On("GetMempool").Return(&types.ReplyTxList{Txs: []*types.Transaction{{}}}, nil)
var testResult interface{} var testResult interface{}
data := &types.ReqNil{} data := &types.ReqNil{}
err := testChain33.GetMempool(data, &testResult) err := testChain33.GetMempool(data, &testResult)
t.Log(err) t.Log(err)
assert.Equal(t, nil, testResult) assert.NotNil(t, testResult)
assert.NotNil(t, err) assert.NoError(t, err)
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
func TestChain33_GetAccountsV2(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
testChain33 := newTestChain33(api)
api.On("WalletGetAccountList", mock.Anything).Return(&types.WalletAccounts{Wallets: []*types.WalletAccount{{}}}, nil)
var testResult interface{}
err := testChain33.GetAccountsV2(nil, &testResult)
t.Log(err)
assert.NotNil(t, testResult)
assert.NoError(t, err)
}
func TestChain33_GetAccounts(t *testing.T) { func TestChain33_GetAccounts(t *testing.T) {
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
testChain33 := newTestChain33(api) testChain33 := newTestChain33(api)
...@@ -1345,3 +1355,121 @@ func TestChain33_GetBalance(t *testing.T) { ...@@ -1345,3 +1355,121 @@ func TestChain33_GetBalance(t *testing.T) {
}) })
} }
} }
func TestChain33_CreateNoBalanceTransaction(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
chain33 := newTestChain33(api)
var result string
err := chain33.CreateNoBalanceTransaction(&types.NoBalanceTx{TxHex: "0a05636f696e73122c18010a281080c2d72f222131477444795771577233553637656a7663776d333867396e7a6e7a434b58434b7120a08d0630a696c0b3f78dd9ec083a2131477444795771577233553637656a7663776d333867396e7a6e7a434b58434b71"}, &result)
assert.NoError(t, err)
}
func TestChain33_ExecWallet(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
in := &rpctypes.ChainExecutor{}
api.On("ExecWallet", mock.Anything).Return(nil, nil)
err := client.ExecWallet(in, &testResult)
assert.NotNil(t, err)
}
func TestChain33_Query(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
in := rpctypes.Query4Jrpc{Execer: "coins"}
api.On("Query", mock.Anything).Return(nil, nil)
err := client.Query(in, &testResult)
assert.NotNil(t, err)
}
func TestChain33_DumpPrivkey(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("DumpPrivkey", mock.Anything).Return(nil, nil)
err := client.DumpPrivkey(types.ReqString{}, &testResult)
assert.NoError(t, err)
}
func TestChain33_GetTotalCoins(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("StoreGetTotalCoins", mock.Anything).Return(nil, nil)
err := client.GetTotalCoins(&types.ReqGetTotalCoins{}, &testResult)
assert.NoError(t, err)
}
func TestChain33_GetFatalFailure(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("GetFatalFailure", mock.Anything).Return(&types.Int32{}, nil)
err := client.GetFatalFailure(nil, &testResult)
assert.NoError(t, err)
}
func TestChain33_DecodeRawTransaction(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
//api.On("GetFatalFailure", mock.Anything).Return(&types.Int32{}, nil)
err := client.DecodeRawTransaction(&types.ReqDecodeRawTransaction{TxHex: "0a05636f696e73122c18010a281080c2d72f222131477444795771577233553637656a7663776d333867396e7a6e7a434b58434b7120a08d0630a696c0b3f78dd9ec083a2131477444795771577233553637656a7663776d333867396e7a6e7a434b58434b71"}, &testResult)
assert.NoError(t, err)
}
func TestChain33_WalletCreateTx(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("WalletCreateTx", mock.Anything).Return(&types.Transaction{}, nil)
err := client.WalletCreateTx(types.ReqCreateTransaction{}, &testResult)
assert.NoError(t, err)
}
func TestChain33_CloseQueue(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("CloseQueue", mock.Anything).Return(nil, nil)
err := client.CloseQueue(nil, &testResult)
assert.True(t, testResult.(*types.Reply).IsOk)
assert.NoError(t, err)
}
func TestChain33_AddSeqCallBack(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("AddSeqCallBack", mock.Anything).Return(&types.Reply{}, nil)
err := client.AddSeqCallBack(nil, &testResult)
assert.NoError(t, err)
}
func TestChain33_ListSeqCallBack(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("ListSeqCallBack", mock.Anything).Return(&types.BlockSeqCBs{}, nil)
err := client.ListSeqCallBack(nil, &testResult)
assert.NoError(t, err)
}
func TestChain33_GetSeqCallBackLastNum(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult interface{}
api.On("GetSeqCallBackLastNum", mock.Anything).Return(&types.Int64{}, nil)
err := client.GetSeqCallBackLastNum(nil, &testResult)
assert.NoError(t, err)
}
func TestChain33_ConvertExectoAddr(t *testing.T) {
api := new(mocks.QueueProtocolAPI)
client := newTestChain33(api)
var testResult string
err := client.ConvertExectoAddr(rpctypes.ExecNameParm{ExecName: "coins"}, &testResult)
assert.NoError(t, err)
}
...@@ -145,6 +145,7 @@ func TestGrpc_Call(t *testing.T) { ...@@ -145,6 +145,7 @@ func TestGrpc_Call(t *testing.T) {
rpcCfg.GrpcFuncWhitelist = []string{"*"} rpcCfg.GrpcFuncWhitelist = []string{"*"}
InitCfg(rpcCfg) InitCfg(rpcCfg)
api := new(mocks.QueueProtocolAPI) api := new(mocks.QueueProtocolAPI)
_ = NewGrpcServer()
server := NewGRpcServer(&qmocks.Client{}, api) server := NewGRpcServer(&qmocks.Client{}, api)
assert.NotNil(t, server) assert.NotNil(t, server)
go server.Listen() go server.Listen()
...@@ -180,3 +181,54 @@ func TestGrpc_Call(t *testing.T) { ...@@ -180,3 +181,54 @@ func TestGrpc_Call(t *testing.T) {
server.Close() server.Close()
mock.AssertExpectationsForObjects(t, api) mock.AssertExpectationsForObjects(t, api)
} }
func TestRPC(t *testing.T) {
cfg := &types.RPC{
JrpcBindAddr: "8801",
GrpcBindAddr: "8802",
Whitlist: []string{"127.0.0.1"},
JrpcFuncBlacklist: []string{"CloseQueue"},
GrpcFuncBlacklist: []string{"CloseQueue"},
EnableTrace: true,
}
InitCfg(cfg)
rpc := New(cfg)
client := &qmocks.Client{}
rpc.SetQueueClient(client)
assert.Equal(t, client, rpc.GetQueueClient())
assert.NotNil(t, rpc.GRPC())
assert.NotNil(t, rpc.JRPC())
}
func TestCheckFuncList(t *testing.T) {
funcName := "abc"
jrpcFuncWhitelist = make(map[string]bool)
assert.False(t, checkJrpcFuncWhitelist(funcName))
jrpcFuncWhitelist["*"] = true
assert.True(t, checkJrpcFuncWhitelist(funcName))
delete(jrpcFuncWhitelist, "*")
jrpcFuncWhitelist[funcName] = true
assert.True(t, checkJrpcFuncWhitelist(funcName))
grpcFuncWhitelist = make(map[string]bool)
assert.False(t, checkGrpcFuncWhitelist(funcName))
grpcFuncWhitelist["*"] = true
assert.True(t, checkGrpcFuncWhitelist(funcName))
delete(grpcFuncWhitelist, "*")
grpcFuncWhitelist[funcName] = true
assert.True(t, checkGrpcFuncWhitelist(funcName))
jrpcFuncBlacklist = make(map[string]bool)
assert.False(t, checkJrpcFuncBlacklist(funcName))
jrpcFuncBlacklist[funcName] = true
assert.True(t, checkJrpcFuncBlacklist(funcName))
grpcFuncBlacklist = make(map[string]bool)
assert.False(t, checkGrpcFuncBlacklist(funcName))
grpcFuncBlacklist[funcName] = true
assert.True(t, checkGrpcFuncBlacklist(funcName))
}
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"encoding/json" "encoding/json"
"testing" "testing"
"github.com/33cn/chain33/client/mocks"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
...@@ -57,6 +58,34 @@ func TestDecodeTx(t *testing.T) { ...@@ -57,6 +58,34 @@ func TestDecodeTx(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
} }
func TestDecodeLog(t *testing.T) {
execer := []byte("coins")
log := &ReceiptLog{}
receipt := &ReceiptData{Ty: 2, Logs: []*ReceiptLog{log}}
_, err := DecodeLog(execer, receipt)
assert.NoError(t, err)
}
func TestConvertWalletTxDetailToJSON(t *testing.T) {
tx := &types.Transaction{Execer: []byte("coins")}
log := &types.ReceiptLog{Ty: 0, Log: []byte("test")}
receipt := &types.ReceiptData{Ty: 0, Logs: []*types.ReceiptLog{log}}
detail := &types.WalletTxDetail{Tx: tx, Receipt: receipt}
in := &types.WalletTxDetails{TxDetails: []*types.WalletTxDetail{detail}}
out := &WalletTxDetails{}
err := ConvertWalletTxDetailToJSON(in, out)
assert.NoError(t, err)
}
func TestServer(t *testing.T) {
api := &mocks.QueueProtocolAPI{}
ch := ChannelClient{QueueProtocolAPI: api}
ch.Init("test", nil, nil, nil)
db := ch.GetCoinsAccountDB()
assert.NotNil(t, db)
}
func TestDecodeTx2(t *testing.T) { func TestDecodeTx2(t *testing.T) {
bdata, err := common.FromHex("0a05636f696e73121018010a0c108084af5f1a05310a320a3320e8b31b30b9b69483d7f9d3f04c3a22314b67453376617969715a4b6866684d66744e3776743267447639486f4d6b393431") bdata, err := common.FromHex("0a05636f696e73121018010a0c108084af5f1a05310a320a3320e8b31b30b9b69483d7f9d3f04c3a22314b67453376617969715a4b6866684d66744e3776743267447639486f4d6b393431")
assert.Nil(t, err) assert.Nil(t, err)
......
...@@ -9,6 +9,7 @@ import ( ...@@ -9,6 +9,7 @@ import (
"testing" "testing"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
...@@ -29,3 +30,37 @@ func TestTypeReflact(t *testing.T) { ...@@ -29,3 +30,37 @@ func TestTypeReflact(t *testing.T) {
assert.Equal(t, int64(10), val.Interface().(*types.AssetsTransfer).GetAmount()) assert.Equal(t, int64(10), val.Interface().(*types.AssetsTransfer).GetAmount())
} }
} }
func TestCoinsType(t *testing.T) {
ty := NewType()
payload := ty.GetPayload()
assert.Equal(t, &CoinsAction{}, payload.(*CoinsAction))
assert.Equal(t, "coins", ty.GetName())
assert.Equal(t, logmap, ty.GetLogMap())
assert.Equal(t, actionName, ty.GetTypeMap())
create := &types.CreateTx{}
tx, err := ty.RPC_Default_Process("transfer", create)
assert.NoError(t, err)
_, err = ty.GetAssets(tx)
assert.NoError(t, err)
}
func TestCoinsPb(t *testing.T) {
b := &proto.Buffer{}
ca := &CoinsAction{Value: &CoinsAction_Transfer{&types.AssetsTransfer{}}}
var err error
transfer := ca.GetTransfer()
assert.NotNil(t, transfer)
err = _CoinsAction_OneofMarshaler(ca, b)
assert.NoError(t, err)
ca.Value = &CoinsAction_Genesis{&types.AssetsGenesis{}}
genesis := ca.GetGenesis()
assert.NotNil(t, genesis)
err = _CoinsAction_OneofMarshaler(ca, b)
assert.NoError(t, err)
}
...@@ -7,6 +7,9 @@ package types ...@@ -7,6 +7,9 @@ package types
import ( import (
"testing" "testing"
rpctypes "github.com/33cn/chain33/rpc/types"
"github.com/33cn/chain33/types"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
...@@ -26,9 +29,80 @@ func TestCheckExpireOpt(t *testing.T) { ...@@ -26,9 +29,80 @@ func TestCheckExpireOpt(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "14", str) assert.Equal(t, "14", str)
expire = ""
_, err = CheckExpireOpt(expire)
assert.Error(t, err)
expire = "H:-123"
_, err = CheckExpireOpt(expire)
assert.Error(t, err)
expire = "-123"
_, err = CheckExpireOpt(expire)
assert.Error(t, err)
expire = "H:123" expire = "H:123"
str, err = CheckExpireOpt(expire) str, err = CheckExpireOpt(expire)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "H:123", str) assert.Equal(t, "H:123", str)
} }
func TestDecodeTransaction(t *testing.T) {
tx := &rpctypes.Transaction{
Execer: "coins",
}
result := DecodeTransaction(tx)
assert.Equal(t, result.Execer, "coins")
}
func TestDecodeAccount(t *testing.T) {
precision := int64(1e8)
acc := &types.Account{
Currency: 2,
Balance: 3 * precision,
Frozen: 4 * precision,
Addr: "0x123",
}
accResult := DecodeAccount(acc, precision)
assert.Equal(t, &AccountResult{2, "3.0000", "4.0000", "0x123"}, accResult)
}
func TestCreateRawTx(t *testing.T) {
var err error
_, err = CreateRawTx(&cobra.Command{}, "", 0, "", false, "", "")
assert.Nil(t, err)
_, err = CreateRawTx(&cobra.Command{}, "", 0, "", false, "", "coins")
assert.Nil(t, err)
_, err = CreateRawTx(&cobra.Command{}, "", 0, "", true, "", "")
assert.Nil(t, err)
_, err = CreateRawTx(&cobra.Command{}, "", -1, "", false, "", "")
assert.Equal(t, types.ErrAmount, err)
_, err = CreateRawTx(&cobra.Command{}, "", 1e10, "", false, "", "")
assert.Equal(t, types.ErrAmount, err)
_, err = CreateRawTx(&cobra.Command{}, "", 0, "", false, "", "coins-")
assert.Equal(t, types.ErrExecNameNotMatch, err)
}
func TestGetExecAddr(t *testing.T) {
_, err := GetExecAddr("coins")
assert.Nil(t, err)
}
func TestFormatAmountValue2Display(t *testing.T) {
var amount int64 = 1e8
s := FormatAmountValue2Display(amount)
assert.Equal(t, "1.0000", s)
}
func TestGetAmountValue(t *testing.T) {
n := GetAmountValue(&cobra.Command{}, "")
assert.Equal(t, int64(0), n)
}
func TestGetRealExecName(t *testing.T) {
s := getRealExecName("user.p.fzmtest.", "user.p.game")
assert.Equal(t, "user.p.game", s)
s = getRealExecName("user.p.fzmtest.", "game")
assert.Equal(t, "user.p.fzmtest.game", s)
}
...@@ -120,3 +120,76 @@ func TestAllow(t *testing.T) { ...@@ -120,3 +120,76 @@ func TestAllow(t *testing.T) {
assert.Equal(t, types.ErrNotAllow, demo.Allow(tx, 0)) assert.Equal(t, types.ErrNotAllow, demo.Allow(tx, 0))
assert.Equal(t, false, demo.IsFriend(nil, nil, nil)) assert.Equal(t, false, demo.IsFriend(nil, nil, nil))
} }
func TestDriverBase(t *testing.T) {
demo := newdemoApp().(*demoApp)
demo.SetExecutorType(nil)
assert.Nil(t, demo.GetPayloadValue())
assert.Nil(t, demo.GetExecutorType())
assert.True(t, demo.ExecutorOrder() == 0)
assert.Nil(t, demo.GetFuncMap())
demo.SetIsFree(false)
assert.False(t, demo.IsFree())
tx := &types.Transaction{Execer: []byte("demo"), To: ExecAddress("demo"), GroupCount: 1}
t.Log("addr:", ExecAddress("demo"))
_, err := demo.ExecLocal(tx, nil, 0)
assert.NoError(t, err)
_, err = demo.ExecDelLocal(tx, nil, 0)
assert.NoError(t, err)
_, err = demo.Exec(tx, 0)
assert.NoError(t, err)
err = demo.CheckTx(tx, 0)
assert.NoError(t, err)
txs := []*types.Transaction{tx}
demo.SetTxs(txs)
assert.Equal(t, txs, demo.GetTxs())
_, err = demo.GetTxGroup(0)
assert.Equal(t, types.ErrTxGroupFormat, err)
demo.SetReceipt(nil)
assert.Nil(t, demo.GetReceipt())
demo.SetLocalDB(nil)
assert.Nil(t, demo.GetLocalDB())
assert.Nil(t, demo.GetStateDB())
assert.True(t, demo.GetHeight() == 0)
assert.True(t, demo.GetBlockTime() == 0)
assert.True(t, demo.GetDifficulty() == 0)
assert.Equal(t, "demo", demo.GetName())
assert.Equal(t, "demo", demo.GetCurrentExecName())
name := demo.GetActionName(tx)
assert.Equal(t, "unknown", name)
assert.True(t, demo.CheckSignatureData(tx, 0))
assert.NotNil(t, demo.GetCoinsAccount())
assert.False(t, demo.CheckReceiptExecOk())
err = CheckAddress("1HUiTRFvp6HvW6eacgV9EoBSgroRDiUsMs", 0)
assert.NoError(t, err)
}
func TestDriverBase_Query(t *testing.T) {
dir, ldb, kvdb := util.CreateTestDB()
defer util.CloseTestDB(dir, ldb)
demo := newdemoApp().(*demoApp)
demo.SetLocalDB(kvdb)
addr := &types.ReqAddr{Addr: "1HUiTRFvp6HvW6eacgV9EoBSgroRDiUsMs", Count: 1, Direction: 1}
kvdb.Set(types.CalcTxAddrHashKey(addr.GetAddr(), ""), types.Encode(&types.ReplyTxInfo{}))
_, err := demo.GetTxsByAddr(addr)
assert.Equal(t, types.ErrNotFound, err)
addr.Height = -1
_, err = demo.GetTxsByAddr(addr)
assert.NoError(t, err)
c, err := demo.GetPrefixCount(&types.ReqKey{Key: types.CalcTxAddrHashKey(addr.GetAddr(), "")})
assert.NoError(t, err)
assert.True(t, c.(*types.Int64).Data == 1)
_, err = demo.GetAddrTxsCount(&types.ReqKey{Key: types.CalcTxAddrHashKey(addr.GetAddr(), "")})
assert.NoError(t, err)
_, err = demo.Query("", nil)
assert.Equal(t, types.ErrActionNotSupport, err)
}
...@@ -205,3 +205,16 @@ func TestTokenFinisher(t *testing.T) { ...@@ -205,3 +205,16 @@ func TestTokenFinisher(t *testing.T) {
assert.Equal(t, reply.Key, "token-finisher") assert.Equal(t, reply.Key, "token-finisher")
assert.Equal(t, reply.Value, "[1FCX9XJTZXvZteagTrefJEBPZMt8BFmdoi]") assert.Equal(t, reply.Value, "[1FCX9XJTZXvZteagTrefJEBPZMt8BFmdoi]")
} }
func TestModify(t *testing.T) {
manager := new(Manage)
log := &types.ReceiptLog{Ty: 0, Log: types.Encode(&types.ReceiptConfig{Prev: &types.ConfigItem{}, Current: &types.ConfigItem{}})}
receipt := &types.ReceiptData{Logs: []*types.ReceiptLog{log}}
_, err := manager.ExecDelLocal_Modify(nil, nil, receipt, 0)
assert.NoError(t, err)
_, err = manager.ExecLocal_Modify(nil, nil, receipt, 0)
assert.NoError(t, err)
}
...@@ -75,6 +75,11 @@ func TestKVCreator(t *testing.T) { ...@@ -75,6 +75,11 @@ func TestKVCreator(t *testing.T) {
assert.Equal(t, types.ErrNotFound, err) assert.Equal(t, types.ErrNotFound, err)
_, err = creator.Get([]byte("c1")) _, err = creator.Get([]byte("c1"))
assert.Equal(t, types.ErrNotFound, err) assert.Equal(t, types.ErrNotFound, err)
creator = NewKVCreator(kvdb, []byte("prefix-"), nil)
creator.AddKVListOnly([]*types.KeyValue{{Key: []byte("k"), Value: []byte("v")}})
creator.DelRollbackKV()
creator.AddToLogs(nil)
} }
func TestHeightIndexStr(t *testing.T) { func TestHeightIndexStr(t *testing.T) {
......
...@@ -5,9 +5,8 @@ ...@@ -5,9 +5,8 @@
package store package store
import ( import (
"testing"
"os" "os"
"testing"
"github.com/33cn/chain33/common/log" "github.com/33cn/chain33/common/log"
"github.com/33cn/chain33/queue" "github.com/33cn/chain33/queue"
...@@ -153,4 +152,40 @@ func TestBaseStore_Queue(t *testing.T) { ...@@ -153,4 +152,40 @@ func TestBaseStore_Queue(t *testing.T) {
assert.NotNil(t, resp) assert.NotNil(t, resp)
assert.Equal(t, int64(types.EventStoreDel), resp.Ty) assert.Equal(t, int64(types.EventStoreDel), resp.Ty)
list := &types.StoreList{StateHash: EmptyRoot[:]}
msg = queueClinet.NewMessage("store", types.EventStoreList, list)
err = queueClinet.Send(msg, true)
assert.Nil(t, err)
resp, err = queueClinet.Wait(msg)
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, int64(types.EventStoreListReply), resp.Ty)
}
func TestSubStore(t *testing.T) {
storelistQuery := NewStoreListQuery(&storeChild{}, &types.StoreList{StateHash: EmptyRoot[:], Mode: 1})
ok := storelistQuery.IterateCallBack([]byte("abc"), nil)
_ = storelistQuery.Run()
assert.True(t, ok)
storelistQuery = NewStoreListQuery(&storeChild{}, &types.StoreList{StateHash: EmptyRoot[:], Count: 2, Mode: 1})
ok = storelistQuery.IterateCallBack([]byte("abc"), nil)
assert.False(t, ok)
storelistQuery = NewStoreListQuery(&storeChild{}, &types.StoreList{StateHash: EmptyRoot[:], Suffix: []byte("bc"), Mode: 2})
ok = storelistQuery.IterateCallBack([]byte("abc"), nil)
assert.True(t, ok)
}
func TestRegAndLoad(t *testing.T) {
Reg("test", func(cfg *types.Store, sub []byte) queue.Module {
return nil
})
_, err := Load("test")
assert.NoError(t, err)
_, err = Load("test2")
assert.Equal(t, types.ErrNotFound, err)
} }
...@@ -32,6 +32,9 @@ func TestStart(t *testing.T) { ...@@ -32,6 +32,9 @@ func TestStart(t *testing.T) {
cfg, _ := types.InitCfg("../cmd/chain33/chain33.test.toml") cfg, _ := types.InitCfg("../cmd/chain33/chain33.test.toml")
health.Start(cfg.Health) health.Start(cfg.Health)
time.Sleep(time.Second * 3) time.Sleep(time.Second * 3)
api.On("IsSync").Return(&types.Reply{IsOk: false}, nil)
health.Start(cfg.Health)
time.Sleep(time.Second * 3)
health.Close() health.Close()
time.Sleep(time.Second * 1) time.Sleep(time.Second * 1)
} }
......
...@@ -5,15 +5,20 @@ ...@@ -5,15 +5,20 @@
package util package util
import ( import (
"errors"
"sync/atomic"
"testing" "testing"
"github.com/33cn/chain33/common" "github.com/33cn/chain33/common"
"github.com/33cn/chain33/common/address" "github.com/33cn/chain33/common/address"
log "github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/queue" "github.com/33cn/chain33/queue"
qmocks "github.com/33cn/chain33/queue/mocks"
_ "github.com/33cn/chain33/system/crypto/secp256k1"
_ "github.com/33cn/chain33/system/dapp/coins/types"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
_ "github.com/33cn/chain33/system/dapp/coins/types"
) )
func TestMakeStringUpper(t *testing.T) { func TestMakeStringUpper(t *testing.T) {
...@@ -225,3 +230,91 @@ func TestMockModule(t *testing.T) { ...@@ -225,3 +230,91 @@ func TestMockModule(t *testing.T) {
assert.Equal(t, reply.GetIsOk(), false) assert.Equal(t, reply.GetIsOk(), false)
assert.Equal(t, reply.GetMsg(), []byte("mock mempool module not handle message 1")) assert.Equal(t, reply.GetMsg(), []byte("mock mempool module not handle message 1"))
} }
func TestJSONPrint(t *testing.T) {
JSONPrint(t, &types.Reply{})
}
type testClient struct {
qmocks.Client
}
var gid int64
func (t *testClient) NewMessage(topic string, ty int64, data interface{}) *queue.Message {
id := atomic.AddInt64(&gid, 1)
return queue.NewMessage(id, topic, ty, data)
}
func (t *testClient) Wait(in *queue.Message) (*queue.Message, error) {
switch in.Ty {
case types.EventTxHashList:
return &queue.Message{Data: &types.TxHashList{}}, nil
case types.EventExecTxList:
return &queue.Message{Data: &types.Receipts{Receipts: []*types.Receipt{{Ty: 2}, {Ty: types.ExecErr}}}}, nil
case types.EventStoreMemSet:
return &queue.Message{Data: &types.ReplyHash{}}, nil
case types.EventStoreRollback:
return &queue.Message{Data: &types.ReplyHash{}}, nil
case types.EventStoreCommit:
return &queue.Message{Data: &types.ReplyHash{}}, nil
case types.EventCheckBlock:
return &queue.Message{Data: &types.Reply{IsOk: true}}, nil
}
return &queue.Message{}, nil
}
func TestExecBlock(t *testing.T) {
client := &testClient{}
client.On("Send", mock.Anything, mock.Anything).Return(nil)
var txs []*types.Transaction
addr, priv := Genaddress()
tx := CreateCoinsTx(priv, addr, types.Coin)
tx.Sign(types.SECP256K1, priv)
txs = append(txs, tx)
_, _, err := ExecBlock(client, nil, &types.Block{Txs: txs}, false, true, false)
assert.NoError(t, err)
}
func TestExecAndCheckBlock(t *testing.T) {
client := &testClient{}
client.On("Send", mock.Anything, mock.Anything).Return(nil)
_, err := ExecAndCheckBlock(client, &types.Block{}, nil, 0)
assert.NoError(t, err)
_, err = ExecAndCheckBlock2(client, &types.Block{}, nil, nil)
assert.NoError(t, err)
}
func TestCheckBlock(t *testing.T) {
client := &testClient{}
client.On("Send", mock.Anything, mock.Anything).Return(nil)
err := CheckBlock(client, nil)
assert.NoError(t, err)
}
func TestExecKVSetRollback(t *testing.T) {
client := &testClient{}
client.On("Send", mock.Anything, mock.Anything).Return(nil)
err := ExecKVSetRollback(client, nil)
assert.NoError(t, err)
}
func TestCheckDupTx(t *testing.T) {
client := &testClient{}
client.On("Send", mock.Anything, mock.Anything).Return(nil)
var txs []*types.Transaction
addr, priv := Genaddress()
tx := CreateCoinsTx(priv, addr, types.Coin)
tx.Sign(types.SECP256K1, priv)
txs = append(txs, tx)
_, err := CheckDupTx(client, txs, 1)
assert.NoError(t, err)
}
func TestReportErrEventToFront(t *testing.T) {
logger := log.New("test")
client := &testClient{}
client.On("Send", mock.Anything, mock.Anything).Return(nil)
ReportErrEventToFront(logger, client, "from", "to", errors.New("test"))
}
...@@ -6,6 +6,13 @@ ...@@ -6,6 +6,13 @@
package basen_test package basen_test
import (
"testing"
"github.com/33cn/chain33/wallet/bipwallet/basen"
"github.com/stretchr/testify/assert"
)
/* /*
func Test(t *testing.T) { gc.TestingT(t) } func Test(t *testing.T) { gc.TestingT(t) }
...@@ -69,3 +76,18 @@ func (s *Suite) TestNoMultiByte(c *gc.C) { ...@@ -69,3 +76,18 @@ func (s *Suite) TestNoMultiByte(c *gc.C) {
"multi-byte characters not supported") "multi-byte characters not supported")
} }
*/ */
func TestBase58(t *testing.T) {
s := basen.Base58.MustRandom(10)
assert.False(t, len(s) == 0)
b, err := basen.Base58.DecodeString(s)
assert.NoError(t, err)
assert.True(t, len(b) == 10)
b, err = basen.Base58.DecodeStringN(s, 12)
assert.NoError(t, err)
assert.True(t, len(b) == 12)
assert.True(t, basen.Base58.Base() == 58)
}
...@@ -124,4 +124,8 @@ func testVectorKeyPairs(t *testing.T, vector testMasterKey) { ...@@ -124,4 +124,8 @@ func testVectorKeyPairs(t *testing.T, vector testMasterKey) {
assert.Equal(t, testChildKey.privKey, privKey.String()) assert.Equal(t, testChildKey.privKey, privKey.String())
assert.Equal(t, testChildKey.pubKey, pubKey.String()) assert.Equal(t, testChildKey.pubKey, pubKey.String())
} }
childPubkey, err := pubKey.NewChildKey(0)
assert.NoError(t, err)
assert.NotNil(t, childPubkey)
} }
...@@ -11,6 +11,7 @@ import ( ...@@ -11,6 +11,7 @@ import (
bip32 "github.com/33cn/chain33/wallet/bipwallet/go-bip32" bip32 "github.com/33cn/chain33/wallet/bipwallet/go-bip32"
bip39 "github.com/33cn/chain33/wallet/bipwallet/go-bip39" bip39 "github.com/33cn/chain33/wallet/bipwallet/go-bip39"
. "github.com/33cn/chain33/wallet/bipwallet/go-bip44" . "github.com/33cn/chain33/wallet/bipwallet/go-bip44"
"github.com/stretchr/testify/assert"
) )
func TestNewKeyFromMnemonic(t *testing.T) { func TestNewKeyFromMnemonic(t *testing.T) {
...@@ -30,6 +31,10 @@ func TestNewKeyFromMnemonic(t *testing.T) { ...@@ -30,6 +31,10 @@ func TestNewKeyFromMnemonic(t *testing.T) {
if ecKey.String() != "xprvA2ziNegvZRfAAUtDsjeS9LvCP1TFXfR3hUzMcJw7oYAhdPqZyiJTMf1ByyLRxvQmGvgbPcG6Q569m26ixWsmgTR3d3PwicrG7hGD7C7seJA" { if ecKey.String() != "xprvA2ziNegvZRfAAUtDsjeS9LvCP1TFXfR3hUzMcJw7oYAhdPqZyiJTMf1ByyLRxvQmGvgbPcG6Q569m26ixWsmgTR3d3PwicrG7hGD7C7seJA" {
t.Errorf("Invalid EC key - %v", ecKey.String()) t.Errorf("Invalid EC key - %v", ecKey.String())
} }
mnemonic = "aaaaaa"
_, err = NewKeyFromMnemonic(mnemonic, bipwallet.TypeFactomFactoids, bip32.FirstHardenedChild, 0, 0)
assert.NotNil(t, err)
} }
func TestNewKeyFromMasterKey(t *testing.T) { func TestNewKeyFromMasterKey(t *testing.T) {
...@@ -60,6 +65,9 @@ func TestNewKeyFromMasterKey(t *testing.T) { ...@@ -60,6 +65,9 @@ func TestNewKeyFromMasterKey(t *testing.T) {
if ecKey.String() != "xprvA2ziNegvZRfAAUtDsjeS9LvCP1TFXfR3hUzMcJw7oYAhdPqZyiJTMf1ByyLRxvQmGvgbPcG6Q569m26ixWsmgTR3d3PwicrG7hGD7C7seJA" { if ecKey.String() != "xprvA2ziNegvZRfAAUtDsjeS9LvCP1TFXfR3hUzMcJw7oYAhdPqZyiJTMf1ByyLRxvQmGvgbPcG6Q569m26ixWsmgTR3d3PwicrG7hGD7C7seJA" {
t.Errorf("Invalid EC key - %v", ecKey.String()) t.Errorf("Invalid EC key - %v", ecKey.String())
} }
_, err = NewKeyFromMasterKey(&bip32.Key{}, bipwallet.TypeFactomFactoids, bip32.FirstHardenedChild, 0, 0)
assert.NotNil(t, err)
} }
/* /*
......
...@@ -14,12 +14,12 @@ import ( ...@@ -14,12 +14,12 @@ import (
"github.com/33cn/chain33/common/crypto" "github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/queue" "github.com/33cn/chain33/queue"
"github.com/33cn/chain33/store" "github.com/33cn/chain33/store"
_ "github.com/33cn/chain33/system"
"github.com/33cn/chain33/types" "github.com/33cn/chain33/types"
"github.com/33cn/chain33/util" "github.com/33cn/chain33/util"
wcom "github.com/33cn/chain33/wallet/common"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
_ "github.com/33cn/chain33/system"
) )
func init() { func init() {
...@@ -47,6 +47,8 @@ var ( ...@@ -47,6 +47,8 @@ var (
ToAddr1 string ToAddr1 string
ToAddr2 string ToAddr2 string
AddrPrivKey string AddrPrivKey string
addr string
priv crypto.PrivKey
) )
func blockchainModProc(q queue.Queue) { func blockchainModProc(q queue.Queue) {
...@@ -93,12 +95,14 @@ func blockchainModProc(q queue.Queue) { ...@@ -93,12 +95,14 @@ func blockchainModProc(q queue.Queue) {
msg.Reply(client.NewMessage("", types.EventReplyBlockHeight, &types.ReplyBlockHeight{Height: 1})) msg.Reply(client.NewMessage("", types.EventReplyBlockHeight, &types.ReplyBlockHeight{Height: 1}))
} else if msg.Ty == types.EventIsSync { } else if msg.Ty == types.EventIsSync {
msg.Reply(client.NewMessage("", types.EventReplyIsSync, &types.IsCaughtUp{Iscaughtup: true})) msg.Reply(client.NewMessage("", types.EventReplyIsSync, &types.IsCaughtUp{Iscaughtup: true}))
} else if msg.Ty == types.EventQueryTx {
msg.Reply(client.NewMessage("", types.EventTransactionDetail, &types.TransactionDetail{Receipt: &types.ReceiptData{Ty: types.ExecOk}}))
} }
} }
}() }()
go func() { go func() {
client := q.Client() client := q.Client()
client.Sub("execs") client.Sub("exec")
for msg := range client.Recv() { for msg := range client.Recv() {
walletlog.Error("execs", "msg.Ty", msg.Ty) walletlog.Error("execs", "msg.Ty", msg.Ty)
if msg.Ty == types.EventBlockChainQuery { if msg.Ty == types.EventBlockChainQuery {
...@@ -181,6 +185,9 @@ func TestWallet(t *testing.T) { ...@@ -181,6 +185,9 @@ func TestWallet(t *testing.T) {
testSignRawTx(t, wallet) testSignRawTx(t, wallet)
testsetFatalFailure(t, wallet) testsetFatalFailure(t, wallet)
testgetFatalFailure(t, wallet) testgetFatalFailure(t, wallet)
testWallet(t, wallet)
testSendTx(t, wallet)
} }
//ProcWalletLock //ProcWalletLock
...@@ -737,3 +744,75 @@ func testgetFatalFailure(t *testing.T, wallet *Wallet) { ...@@ -737,3 +744,75 @@ func testgetFatalFailure(t *testing.T, wallet *Wallet) {
println("testgetFatalFailure end") println("testgetFatalFailure end")
println("--------------------------") println("--------------------------")
} }
func testWallet(t *testing.T, wallet *Wallet) {
println("test wallet begin")
addr, priv = util.Genaddress()
bpriv := wcom.CBCEncrypterPrivkey([]byte(wallet.Password), priv.Bytes())
was := &types.WalletAccountStore{Privkey: common.ToHex(bpriv), Label: "test", Addr: addr, TimeStamp: time.Now().String()}
err := wallet.SetWalletAccount(false, addr, was)
assert.NoError(t, err)
was1, err := wallet.GetAccountByAddr(addr)
assert.NoError(t, err)
assert.Equal(t, was.Privkey, was1.Privkey)
was2, err := wallet.GetAccountByLabel("test")
assert.NoError(t, err)
assert.Equal(t, was.Privkey, was2.Privkey)
priv2, err := wallet.GetPrivKeyByAddr(addr)
assert.NoError(t, err)
assert.Equal(t, priv, priv2)
_, err = wallet.GetWalletAccounts()
assert.NoError(t, err)
t.Log("password:", wallet.Password)
wallet.walletStore.SetWalletPassword("Newpass2")
assert.Equal(t, "Newpass2", wallet.walletStore.GetWalletPassword())
err = wallet.walletStore.SetFeeAmount(1e5)
assert.NoError(t, err)
fee := wallet.walletStore.GetFeeAmount(1e4)
assert.Equal(t, int64(1e5), fee)
println("test wallet end")
wallet.GetConfig()
wallet.GetMutex()
wallet.GetDBStore()
wallet.GetSignType()
wallet.GetPassword()
wallet.Nonce()
wallet.GetRandom()
wallet.GetBlockHeight()
wallet.GetWalletDone()
wallet.GetLastHeader()
wallet.IsClose()
wallet.AddWaitGroup(1)
wallet.WaitGroupDone()
wallet.RegisterMineStatusReporter(nil)
}
func testSendTx(t *testing.T, wallet *Wallet) {
ok := wallet.IsCaughtUp()
assert.True(t, ok)
_, err := wallet.GetBalance(addr, "coins")
assert.NoError(t, err)
_, err = wallet.GetAllPrivKeys()
assert.NoError(t, err)
hash, err := wallet.SendTransaction(&types.ReceiptAccountTransfer{}, []byte("coins"), priv, ToAddr1)
assert.NoError(t, err)
//wallet.WaitTx(hash)
wallet.WaitTxs([][]byte{hash})
hash, err = wallet.SendTransaction(&types.ReceiptAccountTransfer{}, []byte("test"), priv, ToAddr1)
assert.NoError(t, err)
t.Log(string(hash))
err = wallet.sendTransactionWait(&types.ReceiptAccountTransfer{}, []byte("test"), priv, ToAddr1)
assert.NoError(t, err)
_, err = wallet.getMinerColdAddr(addr)
assert.Equal(t, types.ErrActionNotSupport, err)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment