From 55cb9d174f2b5a50dd202d6a95cf0ba2ea443bb3 Mon Sep 17 00:00:00 2001 From: Alex Willmer Date: Sun, 29 Mar 2020 17:40:47 +0100 Subject: [PATCH] utils: Add tests for Packer.PackFixedByteSlices & UnpackFixedByteSlices --- utils/wrappers/packing.go | 4 ++- utils/wrappers/packing_test.go | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/utils/wrappers/packing.go b/utils/wrappers/packing.go index da9bfc7..d4c0045 100644 --- a/utils/wrappers/packing.go +++ b/utils/wrappers/packing.go @@ -242,7 +242,9 @@ func (p *Packer) PackFixedByteSlices(byteSlices [][]byte) { } } -// UnpackFixedByteSlices unpack a byte slice slice to the byte array +// UnpackFixedByteSlices returns a byte slice slice from the byte array. +// Each byte slice has the specified size. The number of byte slices is +// read from the byte array. func (p *Packer) UnpackFixedByteSlices(size int) [][]byte { sliceSize := p.UnpackInt() bytes := [][]byte(nil) diff --git a/utils/wrappers/packing_test.go b/utils/wrappers/packing_test.go index 3aacd14..8194f55 100644 --- a/utils/wrappers/packing_test.go +++ b/utils/wrappers/packing_test.go @@ -5,6 +5,7 @@ package wrappers import ( "bytes" + "reflect" "testing" ) @@ -292,6 +293,53 @@ func TestPackerUnpackBytes(t *testing.T) { } } +func TestPackerPackFixedByteSlices(t *testing.T) { + p := Packer{MaxSize: 10} + + p.PackFixedByteSlices([][]byte{[]byte("Ava"), []byte("Eva")}) + + if p.Errored() { + t.Fatal(p.Err) + } + + if size := len(p.Bytes); size != 10 { + t.Fatalf("Packer.PackFixedByteSlices wrote %d byte(s) but expected %d byte(s)", size, 13) + } + + expected := []byte("\x00\x00\x00\x02AvaEva") + if !bytes.Equal(p.Bytes, expected) { + t.Fatalf("Packer.PackPackFixedByteSlicesBytes wrote:\n%v\nExpected:\n%v", p.Bytes, expected) + } + + p.PackFixedByteSlices([][]byte{[]byte("Ava"), []byte("Eva")}) + if !p.Errored() { + t.Fatal("Packer.PackFixedByteSlices did not fail when attempt was beyond p.MaxSize") + } +} + +func TestPackerUnpackFixedByteSlices(t *testing.T) { + var ( + p = Packer{Bytes: []byte("\x00\x00\x00\x02AvaEva")} + actual = p.UnpackFixedByteSlices(3) + expected = [][]byte{[]byte("Ava"), []byte("Eva")} + expectedLen = 10 + ) + if p.Errored() { + t.Fatalf("Packer.UnpackFixedByteSlices unexpectedly raised %s", p.Err) + } else if !reflect.DeepEqual(actual, expected) { + t.Fatalf("Packer.UnpackFixedByteSlices returned %d, but expected %d", actual, expected) + } else if p.Offset != expectedLen { + t.Fatalf("Packer.UnpackFixedByteSlices left Offset %d, expected %d", p.Offset, expectedLen) + } + + actual = p.UnpackFixedByteSlices(3) + if !p.Errored() { + t.Fatalf("Packer.UnpackFixedByteSlices should have set error, due to attempted out of bounds read") + } else if actual != nil { + t.Fatalf("Packer.UnpackFixedByteSlices returned %v, expected sentinal value %v", actual, nil) + } +} + func TestPackerString(t *testing.T) { p := Packer{MaxSize: 5}