]> Sergey Matveev's repositories - btrtrc.git/blobdiff - peer_protocol/protocol_test.go
Drop support for go 1.20
[btrtrc.git] / peer_protocol / protocol_test.go
index b818a2e260be064d003dbb633103899185073b22..df01a1a676f49dc26907f6ab135864b590b6b577 100644 (file)
@@ -3,9 +3,10 @@ package peer_protocol
 import (
        "bufio"
        "bytes"
-       "io"
        "strings"
        "testing"
+
+       "github.com/stretchr/testify/assert"
 )
 
 func TestBinaryReadSliceOfPointers(t *testing.T) {
@@ -26,10 +27,8 @@ func TestBinaryReadSliceOfPointers(t *testing.T) {
 }
 
 func TestConstants(t *testing.T) {
-       // check that iota works as expected in the const block
-       if NotInterested != 3 {
-               t.FailNow()
-       }
+       assert.EqualValues(t, 3, NotInterested)
+       assert.EqualValues(t, 14, HaveAll)
 }
 
 func TestBitfieldEncode(t *testing.T) {
@@ -83,7 +82,7 @@ func TestShortRead(t *testing.T) {
        }
        msg := new(Message)
        err := dec.Decode(msg)
-       if !strings.Contains(err.Error(), "short read") {
+       if !strings.Contains(err.Error(), "1 unused bytes in message type Choke") {
                t.Fatal(err)
        }
 }
@@ -103,8 +102,53 @@ func TestUnexpectedEOF(t *testing.T) {
                        MaxLength: 42,
                }
                err := dec.Decode(msg)
-               if err != io.ErrUnexpectedEOF {
-                       t.Fatal(err)
+               if err == nil {
+                       t.Fatalf("expected an error decoding %q", stream)
                }
        }
 }
+
+func TestMarshalKeepalive(t *testing.T) {
+       b, err := (Message{
+               Keepalive: true,
+       }).MarshalBinary()
+       if err != nil {
+               t.Fatalf("error marshalling keepalive: %s", err)
+       }
+       bs := string(b)
+       const expected = "\x00\x00\x00\x00"
+       if bs != expected {
+               t.Fatalf("marshalled keepalive is %q, expected %q", bs, expected)
+       }
+}
+
+func TestMarshalPortMsg(t *testing.T) {
+       b, err := (Message{
+               Type: Port,
+               Port: 0xaabb,
+       }).MarshalBinary()
+       if err != nil {
+               t.Fatal(err)
+       }
+       if string(b) != "\x00\x00\x00\x03\x09\xaa\xbb" {
+               t.FailNow()
+       }
+}
+
+func TestUnmarshalPortMsg(t *testing.T) {
+       var m Message
+       d := Decoder{
+               R:         bufio.NewReader(bytes.NewBufferString("\x00\x00\x00\x03\x09\xaa\xbb")),
+               MaxLength: 8,
+       }
+       err := d.Decode(&m)
+       if err != nil {
+               t.Fatal(err)
+       }
+       if m.Type != Port {
+               t.FailNow()
+       }
+       if m.Port != 0xaabb {
+               t.FailNow()
+       }
+}