github.com/anacrolix/torrent@v1.61.0/peer_protocol/ut-holepunch/ut-holepunch_test.go (about)

     1  package utHolepunch
     2  
     3  import (
     4  	"bytes"
     5  	"net/netip"
     6  	"testing"
     7  
     8  	qt "github.com/go-quicktest/qt"
     9  )
    10  
    11  var exampleMsgs = []Msg{
    12  	{
    13  		MsgType:  Rendezvous,
    14  		AddrPort: netip.MustParseAddrPort("[1234::1]:42069"),
    15  		ErrCode:  16777216,
    16  	},
    17  	{
    18  		MsgType:  Connect,
    19  		AddrPort: netip.MustParseAddrPort("1.2.3.4:42069"),
    20  		ErrCode:  16777216,
    21  	},
    22  }
    23  
    24  func TestUnmarshalMsg(t *testing.T) {
    25  	for _, m := range exampleMsgs {
    26  		b, err := m.MarshalBinary()
    27  		qt.Assert(t, qt.IsNil(err))
    28  		expectedLen := 24
    29  		if m.AddrPort.Addr().Is4() {
    30  			expectedLen = 12
    31  		}
    32  		qt.Check(t, qt.HasLen(b, expectedLen))
    33  		var um Msg
    34  		err = um.UnmarshalBinary(b)
    35  		qt.Assert(t, qt.IsNil(err))
    36  		qt.Check(t, qt.Equals(um, m))
    37  	}
    38  }
    39  
    40  func FuzzMsg(f *testing.F) {
    41  	for _, m := range exampleMsgs {
    42  		emb, err := m.MarshalBinary()
    43  		if err != nil {
    44  			f.Fatal(err)
    45  		}
    46  		f.Add(emb)
    47  	}
    48  	f.Fuzz(func(t *testing.T, b []byte) {
    49  		var m Msg
    50  		err := m.UnmarshalBinary(b)
    51  		if err != nil {
    52  			t.SkipNow()
    53  		}
    54  		mb, err := m.MarshalBinary()
    55  		if err != nil {
    56  			t.Fatal(err)
    57  		}
    58  		if !bytes.Equal(b, mb) {
    59  			t.FailNow()
    60  		}
    61  	})
    62  }