github.com/uber/kraken@v0.1.4/core/peer_id_test.go (about)

     1  // Copyright (c) 2016-2019 Uber Technologies, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  package core
    15  
    16  import (
    17  	"fmt"
    18  	"testing"
    19  
    20  	"github.com/stretchr/testify/require"
    21  	"github.com/uber/kraken/utils/randutil"
    22  	"github.com/uber/kraken/utils/stringset"
    23  )
    24  
    25  func TestAddrHashPeerIDFactory(t *testing.T) {
    26  	require := require.New(t)
    27  
    28  	ip := randutil.IP()
    29  	port := randutil.Port()
    30  	p1, err := AddrHashPeerIDFactory.GeneratePeerID(ip, port)
    31  	require.NoError(err)
    32  	p2, err := AddrHashPeerIDFactory.GeneratePeerID(ip, port)
    33  	require.NoError(err)
    34  	require.Equal(p1.String(), p2.String())
    35  }
    36  
    37  func TestNewPeerIDErrors(t *testing.T) {
    38  	tests := []struct {
    39  		desc  string
    40  		input string
    41  	}{
    42  		{"empty", ""},
    43  		{"invalid hex", "invalid"},
    44  		{"too short", "beef"},
    45  	}
    46  	for _, test := range tests {
    47  		t.Run(test.desc, func(t *testing.T) {
    48  			_, err := NewPeerID(test.input)
    49  			require.Error(t, err)
    50  		})
    51  	}
    52  }
    53  
    54  func TestHashedPeerID(t *testing.T) {
    55  	require := require.New(t)
    56  
    57  	n := 50
    58  
    59  	ids := make(stringset.Set)
    60  	for i := 0; i < n; i++ {
    61  		addr := fmt.Sprintf("%s:%d", randutil.IP(), randutil.Port())
    62  		peerID, err := HashedPeerID(addr)
    63  		require.NoError(err)
    64  		ids.Add(peerID.String())
    65  	}
    66  
    67  	// None of the hashes should conflict.
    68  	require.Len(ids, n)
    69  }
    70  
    71  func TestHashedPeerIDReturnsErrOnEmpty(t *testing.T) {
    72  	require := require.New(t)
    73  
    74  	_, err := HashedPeerID("")
    75  	require.Error(err)
    76  }
    77  
    78  func TestPeerIDCompare(t *testing.T) {
    79  	require := require.New(t)
    80  
    81  	peer1 := PeerIDFixture()
    82  	peer2 := PeerIDFixture()
    83  	if peer1.String() < peer2.String() {
    84  		require.True(peer1.LessThan(peer2))
    85  	} else if peer1.String() > peer2.String() {
    86  		require.True(peer2.LessThan(peer1))
    87  	}
    88  }