Skip to content

Commit

Permalink
Add test for packet read io error (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
at-wat authored Feb 8, 2020
1 parent 39b4b5c commit 9431085
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func readPacket(r io.Reader) (packetType, byte, []byte, error) {
var remainingLength int
for shift := uint(0); ; shift += 7 {
remainingLength |= (int(buf[1]) & 0x7F) << shift
if !(buf[1]&0x80 != 0) {
if buf[1]&0x80 == 0 {
break
}
if _, err := io.ReadFull(r, buf[1:]); err != nil {
Expand Down
23 changes: 23 additions & 0 deletions serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
package mqtt

import (
"bytes"
"context"
"io"
"net"
"testing"
"time"
Expand Down Expand Up @@ -116,3 +118,24 @@ func TestServeParseError(t *testing.T) {
})
}
}

func TestReadPacketError(t *testing.T) {
pkt := []byte{0x10, 0x80, 0x01}
pkt = append(pkt, make([]byte, 128)...)

// Ensure full packet doesn't error
_, _, _, err := readPacket(bytes.NewReader(pkt))
if err != nil {
t.Fatalf("Unexpected error: '%v'", err)
}

for i := 1; i < len(pkt)-1; i++ {
_, _, _, err := readPacket(bytes.NewReader(pkt[:i]))
if err != io.ErrUnexpectedEOF && err != io.EOF {
t.Fatalf(
"Expected error for %d: '%v' or %v'', got: '%v'",
i, io.ErrUnexpectedEOF, io.EOF, err,
)
}
}
}

0 comments on commit 9431085

Please sign in to comment.