github.com/andy2046/gopie@v0.7.0/pkg/jumphash/jumphash_test.go (about)

     1  package jumphash_test
     2  
     3  import (
     4  	"strconv"
     5  	"testing"
     6  
     7  	. "github.com/andy2046/gopie/pkg/jumphash"
     8  )
     9  
    10  var jumphashTest = []struct {
    11  	key      uint64
    12  	buckets  int
    13  	expected int
    14  }{
    15  	{1, 1, 0},
    16  	{42, 57, 43},
    17  	{0xDEAD10CC, 1, 0},
    18  	{0xDEAD10CC, 666, 361},
    19  	{256, 1024, 520},
    20  	{0, -10, 0},
    21  }
    22  
    23  func TestHash(t *testing.T) {
    24  	for _, v := range jumphashTest {
    25  		h := Hash(v.key, v.buckets)
    26  		if h != v.expected {
    27  			t.Errorf("expected bucket for key=%d to be %d, got %d",
    28  				v.key, v.expected, h)
    29  		}
    30  	}
    31  }
    32  
    33  var jumphashStringTest = []struct {
    34  	key      string
    35  	buckets  int
    36  	expected int
    37  }{
    38  	{"localhost", 10, 6},
    39  	{"中国", 10, 1},
    40  }
    41  
    42  func TestHashString(t *testing.T) {
    43  	for _, v := range jumphashStringTest {
    44  		h := HashString(v.key, v.buckets)
    45  		if h != v.expected {
    46  			t.Errorf("invalid bucket for key=%s, expected %d, got %d",
    47  				strconv.Quote(v.key), v.expected, h)
    48  		}
    49  	}
    50  }
    51  
    52  func TestHasher(t *testing.T) {
    53  	for _, v := range jumphashStringTest {
    54  		hasher := New(v.buckets)
    55  		h := hasher.Hash(v.key)
    56  		if h != v.expected {
    57  			t.Errorf("invalid bucket for key=%s, expected %d, got %d",
    58  				strconv.Quote(v.key), v.expected, h)
    59  		}
    60  	}
    61  }
    62  
    63  func BenchmarkHashN100(b *testing.B)   { benchmarkHash(b, 100) }
    64  func BenchmarkHashN1000(b *testing.B)  { benchmarkHash(b, 1000) }
    65  func BenchmarkHashN10000(b *testing.B) { benchmarkHash(b, 10000) }
    66  
    67  func benchmarkHash(b *testing.B, n int) {
    68  	h := New(n)
    69  	for i := 0; i < b.N; i++ {
    70  		if x := h.Hash(strconv.Itoa(i)); x > n {
    71  			b.Fatal("invalid hash:", x)
    72  		}
    73  	}
    74  }