Compare commits

...

2 Commits

Author SHA1 Message Date
4419260cd0 rename TestPacket -> TestPacketEncodeDecode
also, verify encoded bytes to a sample
2023-11-22 20:04:53 -06:00
9df5a3d0d5 start packet_test.go; minor packet.go refactoring 2023-11-22 18:18:22 -06:00
2 changed files with 55 additions and 8 deletions

View File

@ -61,10 +61,9 @@ func (pkt Packet) encodeStructField(field reflect.StructField, value reflect.Val
// write padding bytes // write padding bytes
pad, err := strconv.Atoi(field.Tag.Get("pad")) pad, err := strconv.Atoi(field.Tag.Get("pad"))
if err == nil { if err == nil {
for i := 0; i < pad; i++ { dummy := make([]byte, pad)
if _, err := pkt.readWriter.Write([]byte{0}); err != nil { if _, err := pkt.readWriter.Write(dummy); err != nil {
return err return err
}
} }
} }
@ -126,10 +125,9 @@ func (pkt Packet) decodeStructField(field reflect.StructField, value reflect.Val
// consume padding bytes // consume padding bytes
pad, err := strconv.Atoi(field.Tag.Get("pad")) pad, err := strconv.Atoi(field.Tag.Get("pad"))
if err == nil { if err == nil {
for i := 0; i < pad; i++ { dummy := make([]byte, pad)
if _, err := pkt.readWriter.Read([]byte{0}); err != nil { if _, err := pkt.readWriter.Read(dummy); err != nil {
return err return err
}
} }
} }

View File

@ -0,0 +1,49 @@
package protocol
import (
"bytes"
"testing"
)
type TestPacketData struct {
A int32
B int32
UTF16Str string `size:"32"`
Pad int16 `pad:"2"`
C int32
}
// this is the data we expect to get from encoding the above struct with:
//
// Encode(TestPacketData{
// A: 1,
// B: 2,
// UTF16Str: "hello world",
// C: 3,
// })
var testData = [...]byte{0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x68, 0x00, 0x65, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6f, 0x00, 0x20, 0x00, 0x77, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x6c, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00}
func TestPacketEncodeDecode(t *testing.T) {
pkt := NewPacket(&bytes.Buffer{})
if err := pkt.Encode(TestPacketData{
A: 1,
B: 2,
UTF16Str: "hello world",
C: 3,
}); err != nil {
t.Error(err)
}
if !bytes.Equal(pkt.readWriter.(*bytes.Buffer).Bytes(), testData[:]) {
t.Error("packet data does not match!")
}
var test TestPacketData
if err := pkt.Decode(&test); err != nil {
t.Error(err)
}
if test.A != 1 || test.B != 2 || test.C != 3 || test.UTF16Str != "hello world" {
t.Error("decoded packet data does not match!")
}
}