gitee.com/quant1x/gox@v1.21.2/encoding/binary/struc/fields_test.go (about)

     1  package struc
     2  
     3  import (
     4  	"bytes"
     5  	"reflect"
     6  	"testing"
     7  )
     8  
     9  var refVal = reflect.ValueOf(reference)
    10  
    11  func TestFieldsParse(t *testing.T) {
    12  	if _, err := parseFields(refVal); err != nil {
    13  		t.Fatal(err)
    14  	}
    15  }
    16  
    17  func TestFieldsString(t *testing.T) {
    18  	fields, _ := parseFields(refVal)
    19  	fields.String()
    20  }
    21  
    22  type sizefromStruct struct {
    23  	Size1 uint `struc:"sizeof=Var1"`
    24  	Var1  []byte
    25  	Size2 int `struc:"sizeof=Var2"`
    26  	Var2  []byte
    27  }
    28  
    29  func TestFieldsSizefrom(t *testing.T) {
    30  	var test = sizefromStruct{
    31  		Var1: []byte{1, 2, 3},
    32  		Var2: []byte{4, 5, 6},
    33  	}
    34  	var buf bytes.Buffer
    35  	err := Pack(&buf, &test)
    36  	if err != nil {
    37  		t.Fatal(err)
    38  	}
    39  	err = Unpack(&buf, &test)
    40  	if err != nil {
    41  		t.Fatal(err)
    42  	}
    43  }
    44  
    45  type sizefromStructBad struct {
    46  	Size1 string `struc:"sizeof=Var1"`
    47  	Var1  []byte
    48  }
    49  
    50  func TestFieldsSizefromBad(t *testing.T) {
    51  	var test = &sizefromStructBad{Var1: []byte{1, 2, 3}}
    52  	var buf bytes.Buffer
    53  	defer func() {
    54  		if err := recover(); err == nil {
    55  			t.Fatal("failed to panic on bad sizeof type")
    56  		}
    57  	}()
    58  	Pack(&buf, &test)
    59  }
    60  
    61  type StructWithinArray struct {
    62  	a uint32
    63  }
    64  
    65  type StructHavingArray struct {
    66  	Props [1]StructWithinArray `struc:"[1]StructWithinArray"`
    67  }
    68  
    69  func TestStrucArray(t *testing.T) {
    70  	var buf bytes.Buffer
    71  	a := &StructHavingArray{[1]StructWithinArray{}}
    72  	err := Pack(&buf, a)
    73  	if err != nil {
    74  		t.Fatal(err)
    75  	}
    76  	b := &StructHavingArray{}
    77  	err = Unpack(&buf, b)
    78  	if err != nil {
    79  		t.Fatal(err)
    80  	}
    81  }