package network import ( "bytes" "encoding/binary" "testing" ) const ( readerByteValue byte = 1 readerUint8Value uint8 = 5 readerUint16Value uint16 = 6 readerUint32Value uint32 = 7 readerUint64Value uint64 = 8 readerStringValue = "91011" ) var ( readerBytesValue = []byte{2, 3, 4} ) func TestDataReader(t *testing.T) { buffer := &bytes.Buffer{} err := binary.Write(buffer, binary.BigEndian, readerByteValue) if err != nil { t.Fatal(err) } err = binary.Write(buffer, binary.BigEndian, readerBytesValue) if err != nil { t.Fatal(err) } err = binary.Write(buffer, binary.BigEndian, readerUint8Value) if err != nil { t.Fatal(err) } err = binary.Write(buffer, binary.BigEndian, readerUint16Value) if err != nil { t.Fatal(err) } err = binary.Write(buffer, binary.BigEndian, readerUint32Value) if err != nil { t.Fatal(err) } err = binary.Write(buffer, binary.BigEndian, readerUint64Value) if err != nil { t.Fatal(err) } err = binary.Write(buffer, binary.BigEndian, []byte(readerStringValue)) if err != nil { t.Fatal(err) } reader := NewDataReader(buffer.Bytes()) retByteValue, err := reader.Byte() if err != nil { t.Fatal(err) } if retByteValue != readerByteValue { t.Fatal("byte不正确", err.Error()) } retBytesValue, err := reader.Bytes(len(readerBytesValue)) if err != nil { t.Fatal(err) } if len(retBytesValue) != len(readerBytesValue) { t.Fatal("bytes长度不正确") } for i := 0; i < len(retBytesValue); i++ { if retBytesValue[i] != readerBytesValue[i] { t.Fatal("bytes不正确") } } retUint8Value, err := reader.Uint8() if err != nil { t.Fatal(err) } if retUint8Value != readerUint8Value { t.Fatal("uint8不正确", err.Error()) } retUint16Value, err := reader.Uint16() if err != nil { t.Fatal(err) } if retUint16Value != readerUint16Value { t.Fatal("uint16不正确", err.Error()) } retUint32Value, err := reader.Uint32() if err != nil { t.Fatal(err) } if retUint32Value != readerUint32Value { t.Fatal("uint32不正确", err.Error()) } retUint64Value, err := reader.Uint64() if err != nil { t.Fatal(err) } if retUint64Value != readerUint64Value { t.Fatal("uint64不正确", err.Error()) } retStringValue, err := reader.String(len(readerStringValue)) if err != nil { t.Fatal(err) } if retStringValue != readerStringValue { t.Fatal("uint64不正确", err.Error()) } }