github.com/supragya/TendermintConnector@v0.0.0-20210619045051-113e32b84fb1/_deprecated_chains/cosmos/libs/common/bytes_test.go (about) 1 package common 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 // This is a trivial test for protobuf compatibility. 12 func TestMarshal(t *testing.T) { 13 bz := []byte("hello world") 14 dataB := HexBytes(bz) 15 bz2, err := dataB.Marshal() 16 assert.Nil(t, err) 17 assert.Equal(t, bz, bz2) 18 19 var dataB2 HexBytes 20 err = (&dataB2).Unmarshal(bz) 21 assert.Nil(t, err) 22 assert.Equal(t, dataB, dataB2) 23 } 24 25 // Test that the hex encoding works. 26 func TestJSONMarshal(t *testing.T) { 27 28 type TestStruct struct { 29 B1 []byte 30 B2 HexBytes 31 } 32 33 cases := []struct { 34 input []byte 35 expected string 36 }{ 37 {[]byte(``), `{"B1":"","B2":""}`}, 38 {[]byte(`a`), `{"B1":"YQ==","B2":"61"}`}, 39 {[]byte(`abc`), `{"B1":"YWJj","B2":"616263"}`}, 40 } 41 42 for i, tc := range cases { 43 t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) { 44 ts := TestStruct{B1: tc.input, B2: tc.input} 45 46 // Test that it marshals correctly to JSON. 47 jsonBytes, err := json.Marshal(ts) 48 if err != nil { 49 t.Fatal(err) 50 } 51 assert.Equal(t, string(jsonBytes), tc.expected) 52 53 // Test that unmarshaling works correctly. 54 ts2 := TestStruct{} 55 err = json.Unmarshal(jsonBytes, &ts2) 56 if err != nil { 57 t.Fatal(err) 58 } 59 assert.Equal(t, ts2.B1, tc.input) 60 assert.Equal(t, ts2.B2, HexBytes(tc.input)) 61 }) 62 } 63 }