github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/protocol/vm/types_test.go (about)

     1  package vm
     2  
     3  import (
     4  	"bytes"
     5  	"testing"
     6  )
     7  
     8  func TestBoolBytes(t *testing.T) {
     9  	got := BoolBytes(true)
    10  	want := []byte{1}
    11  	if !bytes.Equal(got, want) {
    12  		t.Errorf("BoolBytes(t) = %x want %x", got, want)
    13  	}
    14  
    15  	got = BoolBytes(false)
    16  	want = []byte{}
    17  	if !bytes.Equal(got, want) {
    18  		t.Errorf("BoolBytes(f) = %x want %x", got, want)
    19  	}
    20  }
    21  
    22  func TestAsBool(t *testing.T) {
    23  	cases := []struct {
    24  		data []byte
    25  		want bool
    26  	}{
    27  		{[]byte{0, 0, 0, 0}, false},
    28  		{[]byte{0}, false},
    29  		{[]byte{}, false},
    30  		{[]byte{1}, true},
    31  		{[]byte{1, 1, 1, 1}, true},
    32  		{[]byte{0, 0, 0, 1}, true},
    33  		{[]byte{1, 0, 0, 0}, true},
    34  		{[]byte{2}, true},
    35  	}
    36  
    37  	for _, c := range cases {
    38  		got := AsBool(c.data)
    39  
    40  		if got != c.want {
    41  			t.Errorf("AsBool(%x) = %v want %v", c.data, got, c.want)
    42  		}
    43  	}
    44  }
    45  
    46  func TestInt64(t *testing.T) {
    47  	cases := []struct {
    48  		num  int64
    49  		data []byte
    50  	}{
    51  		{0, []byte{}},
    52  		{1, []byte{0x01}},
    53  		{255, []byte{0xff}},
    54  		{256, []byte{0x00, 0x01}},
    55  		{1 << 16, []byte{0x00, 0x00, 0x01}},
    56  		{-1, []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
    57  		{-2, []byte{0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
    58  	}
    59  
    60  	for _, c := range cases {
    61  		gotData := Int64Bytes(c.num)
    62  
    63  		if !bytes.Equal(gotData, c.data) {
    64  			t.Errorf("Int64Bytes(%d) = %x want %x", c.num, gotData, c.data)
    65  		}
    66  
    67  		gotNum, _ := AsInt64(c.data)
    68  
    69  		if gotNum != c.num {
    70  			t.Errorf("AsInt64(%x) = %d want %d", c.data, gotNum, c.num)
    71  		}
    72  	}
    73  
    74  	data := []byte{1, 1, 1, 1, 1, 1, 1, 1, 1}
    75  	_, err := AsInt64(data)
    76  	want := ErrBadValue
    77  	if err != want {
    78  		t.Errorf("AsInt64(%x) = %v want %v", data, err, want)
    79  	}
    80  }