gitee.com/quant1x/gox@v1.21.2/encoding/binary/struc/field_test.go (about) 1 package struc 2 3 import ( 4 "bytes" 5 "testing" 6 ) 7 8 type badFloat struct { 9 BadFloat int `struc:"float64"` 10 } 11 12 func TestBadFloatField(t *testing.T) { 13 buf := bytes.NewReader([]byte("00000000")) 14 err := Unpack(buf, &badFloat{}) 15 if err == nil { 16 t.Fatal("failed to error on bad float unpack") 17 } 18 } 19 20 type emptyLengthField struct { 21 Strlen int `struc:"sizeof=Str"` 22 Str []byte 23 } 24 25 func TestEmptyLengthField(t *testing.T) { 26 var buf bytes.Buffer 27 s := &emptyLengthField{0, []byte("test")} 28 o := &emptyLengthField{} 29 if err := Pack(&buf, s); err != nil { 30 t.Fatal(err) 31 } 32 if err := Unpack(&buf, o); err != nil { 33 t.Fatal(err) 34 } 35 if !bytes.Equal(s.Str, o.Str) { 36 t.Fatal("empty length field encode failed") 37 } 38 } 39 40 type fixedSlicePad struct { 41 Field []byte `struc:"[4]byte"` 42 } 43 44 func TestFixedSlicePad(t *testing.T) { 45 var buf bytes.Buffer 46 ref := []byte{0, 0, 0, 0} 47 s := &fixedSlicePad{} 48 if err := Pack(&buf, s); err != nil { 49 t.Fatal(err) 50 } 51 if !bytes.Equal(buf.Bytes(), ref) { 52 t.Fatal("implicit fixed slice pack failed") 53 } 54 if err := Unpack(&buf, s); err != nil { 55 t.Fatal(err) 56 } 57 if !bytes.Equal(s.Field, ref) { 58 t.Fatal("implicit fixed slice unpack failed") 59 } 60 } 61 62 type sliceCap struct { 63 Len int `struc:"sizeof=Field"` 64 Field []byte 65 } 66 67 func TestSliceCap(t *testing.T) { 68 var buf bytes.Buffer 69 tmp := &sliceCap{0, []byte("1234")} 70 if err := Pack(&buf, tmp); err != nil { 71 t.Fatal(err) 72 } 73 tmp.Field = make([]byte, 0, 4) 74 if err := Unpack(&buf, tmp); err != nil { 75 t.Fatal(err) 76 } 77 }