github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/hash/maphash/maphash_test.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package maphash 6 7 import ( 8 "hash" 9 "testing" 10 ) 11 12 func TestUnseededHash(t *testing.T) { 13 m := map[uint64]struct{}{} 14 for i := 0; i < 1000; i++ { 15 h := new(Hash) 16 m[h.Sum64()] = struct{}{} 17 } 18 if len(m) < 900 { 19 t.Errorf("empty hash not sufficiently random: got %d, want 1000", len(m)) 20 } 21 } 22 23 func TestSeededHash(t *testing.T) { 24 s := MakeSeed() 25 m := map[uint64]struct{}{} 26 for i := 0; i < 1000; i++ { 27 h := new(Hash) 28 h.SetSeed(s) 29 m[h.Sum64()] = struct{}{} 30 } 31 if len(m) != 1 { 32 t.Errorf("seeded hash is random: got %d, want 1", len(m)) 33 } 34 } 35 36 func TestHashGrouping(t *testing.T) { 37 b := []byte("foo") 38 h1 := new(Hash) 39 h2 := new(Hash) 40 h2.SetSeed(h1.Seed()) 41 h1.Write(b) 42 for _, x := range b { 43 err := h2.WriteByte(x) 44 if err != nil { 45 t.Fatalf("WriteByte: %v", err) 46 } 47 } 48 if h1.Sum64() != h2.Sum64() { 49 t.Errorf("hash of \"foo\" and \"f\",\"o\",\"o\" not identical") 50 } 51 } 52 53 func TestHashBytesVsString(t *testing.T) { 54 s := "foo" 55 b := []byte(s) 56 h1 := new(Hash) 57 h2 := new(Hash) 58 h2.SetSeed(h1.Seed()) 59 n1, err1 := h1.WriteString(s) 60 if n1 != len(s) || err1 != nil { 61 t.Fatalf("WriteString(s) = %d, %v, want %d, nil", n1, err1, len(s)) 62 } 63 n2, err2 := h2.Write(b) 64 if n2 != len(b) || err2 != nil { 65 t.Fatalf("Write(b) = %d, %v, want %d, nil", n2, err2, len(b)) 66 } 67 if h1.Sum64() != h2.Sum64() { 68 t.Errorf("hash of string and bytes not identical") 69 } 70 } 71 72 func TestHashHighBytes(t *testing.T) { 73 // See issue 34925. 74 const N = 10 75 m := map[uint64]struct{}{} 76 for i := 0; i < N; i++ { 77 h := new(Hash) 78 h.WriteString("foo") 79 m[h.Sum64()>>32] = struct{}{} 80 } 81 if len(m) < N/2 { 82 t.Errorf("from %d seeds, wanted at least %d different hashes; got %d", N, N/2, len(m)) 83 } 84 } 85 86 // Make sure a Hash implements the hash.Hash and hash.Hash64 interfaces. 87 var _ hash.Hash = &Hash{} 88 var _ hash.Hash64 = &Hash{}