github.com/aergoio/aergo@v1.3.1/p2p/p2putil/protobuf_test.go (about) 1 /* 2 * @file 3 * @copyright defined in aergo/LICENSE.txt 4 */ 5 6 package p2putil 7 8 import ( 9 "fmt" 10 "testing" 11 12 "github.com/aergoio/aergo/internal/enc" 13 "github.com/aergoio/aergo/types" 14 "github.com/golang/protobuf/proto" 15 "github.com/stretchr/testify/assert" 16 ) 17 18 var dummyTxHash, _ = enc.ToBytes("4H4zAkAyRV253K5SNBJtBxqUgHEbZcXbWFFc6cmQHY45") 19 20 func Test_MarshalTxResp(t *testing.T) { 21 dummyTx := &types.Tx{Hash: dummyTxHash, Body: &types.TxBody{Payload: []byte("It's a good day to die.")}} 22 txMarshaled, _ := proto.Marshal(dummyTx) 23 txSize := len(dummyTxHash) + 2 + len(txMarshaled) + 2 // hash+ field desc of hash + tx+field desc of tx 24 //fmt.Println("TX : ",hex.EncodeToString(txMarshaled)) 25 emptyMarshaled, _ := proto.Marshal(&types.GetTransactionsResponse{}) 26 emptySize := len(emptyMarshaled) 27 //fmt.Println("EMPTY: ",hex.EncodeToString(emptyMarshaled)) 28 //fmt.Printf("Size of All nil: %d , tx size: %d ",emptySize, txSize) 29 tests := []struct { 30 name string 31 itemSize int 32 expectedSize int 33 }{ 34 // empty 35 {"TEmpty", 0, emptySize}, 36 // single 37 {"TSingle", 1, emptySize + txSize}, 38 // small multi 39 {"T10", 10, emptySize + txSize*10}, 40 // big 41 // boundary 42 {"T50000", 50000, emptySize + txSize*50000}, 43 // TODO: test cases 44 } 45 for _, test := range tests { 46 t.Run(test.name, func(t *testing.T) { 47 hashSlice := make([][]byte, 0, 10) 48 txSlice := make([]*types.Tx, 0, 10) 49 for i := 0; i < test.itemSize; i++ { 50 hashSlice = append(hashSlice, dummyTxHash) 51 txSlice = append(txSlice, dummyTx) 52 } 53 sampleRsp := &types.GetTransactionsResponse{Hashes: hashSlice, Txs: txSlice} 54 actual, err := proto.Marshal(sampleRsp) 55 if err != nil { 56 t.Errorf("Invalid proto error %s", err.Error()) 57 } 58 actualSize := len(actual) 59 cut := 80 60 if actualSize < cut { 61 cut = actualSize 62 } 63 //fmt.Println("ACTUAL: ",hex.EncodeToString(actual[:cut])) 64 65 assert.Equal(t, test.expectedSize, actualSize) 66 67 }) 68 } 69 } 70 71 func Test_calculateFieldDesc(t *testing.T) { 72 sampleSize := make([]byte, 2<<25) 73 tests := []struct { 74 name string 75 valueSize int 76 expected int 77 }{ 78 {"TZero", 0, 0}, 79 {"TSmall", 127, 2}, 80 {"TMedium", 128, 3}, 81 {"TLarge", 16384, 4}, 82 {"TVeryL", 10000000, 5}, 83 {"TOverflow", 2000000000, 6}, 84 // TODO: test cases 85 } 86 for _, test := range tests { 87 t.Run(test.name, func(t *testing.T) { 88 assert.Equal(t, test.expected, CalculateFieldDescSize(test.valueSize)) 89 if test.valueSize <= len(sampleSize) { 90 inputBytes := sampleSize[:test.valueSize] 91 dummy := &types.GetBlockHeadersRequest{Hash: inputBytes} 92 realSize := proto.Size(dummy) 93 assert.Equal(t, realSize, CalculateFieldDescSize(test.valueSize)+len(inputBytes)) 94 } else { 95 fmt.Println(test.name, " is too big to make real ") 96 } 97 }) 98 } 99 }