github.com/devwanda/aphelion-staking@v0.33.9/libs/bytes/bytes_test.go (about)

     1  package bytes
     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  		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  }