github.com/ari-anchor/sei-tendermint@v0.0.0-20230519144642-dc826b7b56bb/libs/bytes/bytes_test.go (about)

     1  package bytes
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strconv"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  // This is a trivial test for protobuf compatibility.
    13  func TestMarshal(t *testing.T) {
    14  	bz := []byte("hello world")
    15  	dataB := HexBytes(bz)
    16  	bz2, err := dataB.Marshal()
    17  	assert.NoError(t, err)
    18  	assert.Equal(t, bz, bz2)
    19  
    20  	var dataB2 HexBytes
    21  	err = (&dataB2).Unmarshal(bz)
    22  	assert.NoError(t, err)
    23  	assert.Equal(t, dataB, dataB2)
    24  }
    25  
    26  // Test that the hex encoding works.
    27  func TestJSONMarshal(t *testing.T) {
    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  		{[]byte("\x1a\x2b\x3c"), `{"B1":"Gis8","B2":"1A2B3C"}`},
    41  	}
    42  
    43  	for i, tc := range cases {
    44  		tc := tc
    45  		t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) {
    46  			ts := TestStruct{B1: tc.input, B2: tc.input}
    47  
    48  			// Test that it marshals correctly to JSON.
    49  			jsonBytes, err := json.Marshal(ts)
    50  			if err != nil {
    51  				t.Fatal(err)
    52  			}
    53  			assert.Equal(t, string(jsonBytes), tc.expected)
    54  
    55  			// TODO do fuzz testing to ensure that unmarshal fails
    56  
    57  			// Test that unmarshaling works correctly.
    58  			ts2 := TestStruct{}
    59  			err = json.Unmarshal(jsonBytes, &ts2)
    60  			if err != nil {
    61  				t.Fatal(err)
    62  			}
    63  			assert.Equal(t, ts2.B1, tc.input)
    64  			assert.Equal(t, string(ts2.B2), string(tc.input))
    65  		})
    66  	}
    67  }
    68  
    69  func TestHexBytes_String(t *testing.T) {
    70  	hs := HexBytes([]byte("test me"))
    71  	if _, err := strconv.ParseInt(hs.String(), 16, 64); err != nil {
    72  		t.Fatal(err)
    73  	}
    74  }