From 771ac243acff3de5133400c5f068ca2e7b84142b Mon Sep 17 00:00:00 2001 From: saji Date: Wed, 3 May 2023 14:00:26 -0500 Subject: [PATCH] fix off by one in api_frame and add more tests --- internal/xbee/api_frame.go | 2 +- internal/xbee/api_frame_test.go | 58 +++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/internal/xbee/api_frame.go b/internal/xbee/api_frame.go index 4b2ef0a..4478720 100644 --- a/internal/xbee/api_frame.go +++ b/internal/xbee/api_frame.go @@ -136,7 +136,7 @@ func parseFrame(frame []byte) ([]byte, error) { return nil, errors.New("incorrect start delimiter") } fsize := len(frame) - if calculateChecksum(frame[3:fsize-1]) != frame[fsize] { + if calculateChecksum(frame[3:fsize-1]) != frame[fsize-1] { return nil, errors.New("checksum mismatch") } return frame[3 : fsize-1], nil diff --git a/internal/xbee/api_frame_test.go b/internal/xbee/api_frame_test.go index d22feff..3a453a2 100644 --- a/internal/xbee/api_frame_test.go +++ b/internal/xbee/api_frame_test.go @@ -1,6 +1,7 @@ package xbee import ( + "bytes" "reflect" "testing" ) @@ -28,6 +29,16 @@ func Test_xbeeFrameSplit(t *testing.T) { wantToken: nil, wantErr: false, }, + { + name: "EOF and empty data", + args: args{ + data: []byte{}, + atEOF: true, + }, + wantAdvance: 0, + wantToken: nil, + wantErr: false, + }, { name: "no start delimiter", args: args{ @@ -125,6 +136,22 @@ func Test_parseFrame(t *testing.T) { want: nil, wantErr: true, }, + { + name: "checksum mismatch", + args: args{ + frame: []byte{0x7E, 0x00, 0x02, 0x23, 0x11, 0xCA}, + }, + want: nil, + wantErr: true, + }, + { + name: "valid packet", + args: args{ + frame: []byte{0x7E, 0x00, 0x02, 0x23, 0x11, 0xCB}, + }, + want: []byte{0x23, 0x11}, + wantErr: false, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -139,3 +166,34 @@ func Test_parseFrame(t *testing.T) { }) } } + +func Test_writeXBeeFrame(t *testing.T) { + type args struct { + data []byte + } + tests := []struct { + name string + args args + wantN int + wantW string + wantErr bool + }{ + // TODO: Add test cases. + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := &bytes.Buffer{} + gotN, err := writeXBeeFrame(w, tt.args.data) + if (err != nil) != tt.wantErr { + t.Errorf("writeXBeeFrame() error = %v, wantErr %v", err, tt.wantErr) + return + } + if gotN != tt.wantN { + t.Errorf("writeXBeeFrame() = %v, want %v", gotN, tt.wantN) + } + if gotW := w.String(); gotW != tt.wantW { + t.Errorf("writeXBeeFrame() = %v, want %v", gotW, tt.wantW) + } + }) + } +}