github.com/vipernet-xyz/tm@v0.34.24/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.Nil(t, err)
    18  	assert.Equal(t, bz, bz2)
    19  
    20  	var dataB2 HexBytes
    21  	err = (&dataB2).Unmarshal(bz)
    22  	assert.Nil(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  	}
    41  
    42  	for i, tc := range cases {
    43  		tc := tc
    44  		t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) {
    45  			ts := TestStruct{B1: tc.input, B2: tc.input}
    46  
    47  			// Test that it marshals correctly to JSON.
    48  			jsonBytes, err := json.Marshal(ts)
    49  			if err != nil {
    50  				t.Fatal(err)
    51  			}
    52  			assert.Equal(t, string(jsonBytes), tc.expected)
    53  
    54  			// TODO do fuzz testing to ensure that unmarshal fails
    55  
    56  			// Test that unmarshaling works correctly.
    57  			ts2 := TestStruct{}
    58  			err = json.Unmarshal(jsonBytes, &ts2)
    59  			if err != nil {
    60  				t.Fatal(err)
    61  			}
    62  			assert.Equal(t, ts2.B1, tc.input)
    63  			assert.Equal(t, ts2.B2, HexBytes(tc.input))
    64  		})
    65  	}
    66  }
    67  
    68  func TestHexBytes_String(t *testing.T) {
    69  	hs := HexBytes([]byte("test me"))
    70  	if _, err := strconv.ParseInt(hs.String(), 16, 64); err != nil {
    71  		t.Fatal(err)
    72  	}
    73  }