123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- package network
- import (
- "bytes"
- "encoding/binary"
- "testing"
- )
- const (
- writerByteValue byte = 1
- writerUint8Value uint8 = 5
- writerUint16Value uint16 = 6
- writerUint32Value uint32 = 7
- writerUint64Value uint64 = 8
- writerStringValue = "91011"
- )
- var (
- writerBytesValue = []byte{2, 3, 4}
- )
- func TestDataWriter(t *testing.T) {
- writer := NewDataWriter()
- err := writer.Byte(writerByteValue)
- if err != nil {
- t.Fatal(err)
- }
- err = writer.Bytes(writerBytesValue)
- if err != nil {
- t.Fatal(err)
- }
- err = writer.Uint8(writerUint8Value)
- if err != nil {
- t.Fatal(err)
- }
- err = writer.Uint16(writerUint16Value)
- if err != nil {
- t.Fatal(err)
- }
- err = writer.Uint32(writerUint32Value)
- if err != nil {
- t.Fatal(err)
- }
- err = writer.Uint64(writerUint64Value)
- if err != nil {
- t.Fatal(err)
- }
- err = writer.String(writerStringValue)
- if err != nil {
- t.Fatal(err)
- }
- readBuffer := bytes.NewReader(writer.GetBytes())
- var retByteValue byte
- err = binary.Read(readBuffer, binary.BigEndian, &retByteValue)
- if err != nil {
- t.Fatal(err)
- }
- if retByteValue != writerByteValue {
- t.Fatal("byte不一致")
- }
- retBytesValue := make([]byte, len(writerBytesValue))
- err = binary.Read(readBuffer, binary.BigEndian, &retBytesValue)
- 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不正确")
- }
- }
- var retUint8Value uint8
- err = binary.Read(readBuffer, binary.BigEndian, &retUint8Value)
- if err != nil {
- t.Fatal(err)
- }
- if retUint8Value != writerUint8Value {
- t.Fatal("uint8不一致")
- }
- var retUint16Value uint16
- err = binary.Read(readBuffer, binary.BigEndian, &retUint16Value)
- if err != nil {
- t.Fatal(err)
- }
- if retUint16Value != writerUint16Value {
- t.Fatal("uint16不一致")
- }
- var retUint32Value uint32
- err = binary.Read(readBuffer, binary.BigEndian, &retUint32Value)
- if err != nil {
- t.Fatal(err)
- }
- if retUint32Value != writerUint32Value {
- t.Fatal("uint32不一致")
- }
- var retUint64Value uint64
- err = binary.Read(readBuffer, binary.BigEndian, &retUint64Value)
- if err != nil {
- t.Fatal(err)
- }
- if retUint64Value != writerUint64Value {
- t.Fatal("uint64不一致")
- }
- retStringByteValue := make([]byte, len(writerStringValue))
- err = binary.Read(readBuffer, binary.BigEndian, &retStringByteValue)
- if err != nil {
- t.Fatal(err)
- }
- if string(retStringByteValue) != writerStringValue {
- t.Fatal("string不一致")
- }
- }
|