hash256_test.go (2489B)
1 package types 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 const SAMPLE_HASH = "9c151c3af838278e3ef57c180c7d031c07aefd12f2ccc1e18f2a1e1c7d0ff163" 10 11 func TestIncorrectHexLength(t *testing.T) { 12 _, err := Hash256FromHexString("AAA") 13 assert.ErrorContains(t, err, "incorrect hash length") 14 } 15 16 func TestIncorrectHexFormat(t *testing.T) { 17 _, err := Hash256FromHexString("9c151c3af838278e3ef57c180c7d031c07aefd12f2ccc1e18f2a1e1c7d0ff16!") 18 assert.ErrorContains(t, err, "incorrect format") 19 } 20 21 func TestCorrectHexFormat(t *testing.T) { 22 hash, err := Hash256FromHexString(SAMPLE_HASH) 23 assert.ErrorIs(t, err, nil) 24 25 assert.Equal(t, SAMPLE_HASH, hash.String()) 26 } 27 28 func TestClone(t *testing.T) { 29 hash, err := Hash256FromHexString(SAMPLE_HASH) 30 assert.ErrorIs(t, err, nil) 31 32 clone := hash.Clone() 33 assert.Equal(t, SAMPLE_HASH, clone.String()) 34 35 assert.True(t, hash.Eq(&clone)) 36 } 37 38 func TestToString(t *testing.T) { 39 hash, err := Hash256FromHexString(SAMPLE_HASH) 40 assert.ErrorIs(t, err, nil) 41 42 assert.Equal(t, SAMPLE_HASH, hash.String()) 43 } 44 45 func TestBitCount(t *testing.T) { 46 assert.Equal(t, 1, BitCount(1)) 47 48 // dec(10) = bin(01100100) 49 assert.Equal(t, 3, BitCount(100)) 50 } 51 52 func TestHammingNorm(t *testing.T) { 53 hash := &Hash256{} 54 hash.SetAll() 55 56 assert.Equal(t, 256, hash.HammingNorm()) 57 58 hash, err := Hash256FromHexString(SAMPLE_HASH) 59 assert.ErrorIs(t, err, nil) 60 assert.Equal(t, 128, hash.HammingNorm()) 61 } 62 63 func TestHammingDistance(t *testing.T) { 64 hash1, err := Hash256FromHexString(SAMPLE_HASH) 65 assert.ErrorIs(t, err, nil) 66 67 hash2 := Hash256{} 68 hash2.ClearAll() 69 70 assert.Equal(t, 128, hash1.HammingDistance(&hash2)) 71 72 hash1 = &Hash256{} 73 hash1.SetAll() 74 hash2 = Hash256{} 75 hash2.ClearAll() 76 77 assert.Equal(t, 256, hash1.HammingDistance(&hash2)) 78 assert.False(t, hash1.HammingDistanceLE(&hash2, 1)) 79 assert.True(t, hash1.HammingDistanceLE(&hash2, 257)) 80 assert.True(t, hash1.HammingDistanceLE(hash1, 0)) 81 } 82 83 func TestBinaryOperations(t *testing.T) { 84 hash, err := Hash256FromHexString(SAMPLE_HASH) 85 assert.ErrorIs(t, err, nil) 86 87 result := hash.BitwiseAND(hash) 88 hash2 := &result 89 assert.True(t, hash2.Eq(hash)) 90 91 hashNegative := hash.BitwiseNOT() 92 result = hash.BitwiseAND(&hashNegative) 93 hash2 = &result 94 hash3 := &Hash256{} 95 assert.True(t, hash2.Eq(hash3)) 96 97 hash_set_all := &Hash256{} 98 hash_set_all.SetAll() 99 100 result = hash.BitwiseOR(&hashNegative) 101 assert.True(t, result.Eq(hash_set_all)) 102 103 result = hash.BitwiseXOR(&hashNegative) 104 assert.True(t, result.Eq(hash_set_all)) 105 }