Skip to content

Commit

Permalink
improve tests
Browse files Browse the repository at this point in the history
Signed-off-by: Florian Lehner <[email protected]>
  • Loading branch information
florianl committed Aug 24, 2024
1 parent e0fdc18 commit e3eff8a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
6 changes: 4 additions & 2 deletions ematch_nbyte.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ type tcfEmNByte struct {

func unmarshalNByteMatch(data []byte, info *NByteMatch) error {
if len(data) < 8 {
return fmt.Errorf("unmarshalNByteMatch: incomplete data")
return fmt.Errorf("unmarshalNByteMatch: incomplete data: %w",
ErrInvalidArg)
}

// We can not unmarshal elements of a non-public struct.
Expand All @@ -29,7 +30,8 @@ func unmarshalNByteMatch(data []byte, info *NByteMatch) error {
needleLen := binary.LittleEndian.Uint16(data[2:4])
info.Layer = uint8(data[4])
if len(data) < (8 + int(needleLen)) {
return fmt.Errorf("unmarshalNByteMatch: incomplete needle")
return fmt.Errorf("unmarshalNByteMatch: invalid needle: %w",
ErrInvalidArg)
}
info.Needle = data[8 : 8+needleLen]

Expand Down
34 changes: 34 additions & 0 deletions ematch_nbyte_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,37 @@ func TestNByteMatch(t *testing.T) {
}
})
}

func TestUnmarshalNByteMatch(t *testing.T) {
tests := map[string]struct {
data []byte
needleLen uint16
err error
}{
"invalid lenght": {
data: []byte{0x0, 0x1, 0x2, 0x3},
err: ErrInvalidArg,
},
"invalid needle": {
data: []byte{0x00, 0x00,
0xaa, 0xaa,
0x01,
0x00, 0x00, 0x00,
0x0a, 0x0b, 0x0c},
err: ErrInvalidArg,
},
}

for name, testcase := range tests {
name := name
testcase := testcase
t.Run(name, func(t *testing.T) {
info := NByteMatch{}
if err := unmarshalNByteMatch(testcase.data, &info); err != nil {
if !errors.Is(err, ErrInvalidArg) {
t.Fatalf("Unexpected error: %v", err)
}
}
})
}
}

0 comments on commit e3eff8a

Please sign in to comment.