haystack_test.gno
2.35 Kb ยท 94 lines
1package haystack
2
3import (
4 "encoding/hex"
5 "testing"
6
7 "gno.land/p/n2p5/haystack/needle"
8)
9
10func TestHaystack(t *testing.T) {
11 t.Parallel()
12
13 t.Run("New", func(t *testing.T) {
14 t.Parallel()
15 h := New()
16 if h == nil {
17 t.Error("New returned nil")
18 }
19 })
20
21 t.Run("Add", func(t *testing.T) {
22 t.Parallel()
23 h := New()
24 n, _ := needle.New(make([]byte, needle.PayloadLength))
25 validNeedleHex := hex.EncodeToString(n.Bytes())
26
27 testTable := []struct {
28 needleHex string
29 err error
30 }{
31 {validNeedleHex, nil},
32 {validNeedleHex, ErrorDuplicateNeedle},
33 {"bad" + validNeedleHex[3:], needle.ErrorInvalidHash},
34 {"XXX" + validNeedleHex[3:], hex.InvalidByteError('X')},
35 {validNeedleHex[:len(validNeedleHex)-2], ErrorNeedleLength},
36 {validNeedleHex + "00", ErrorNeedleLength},
37 {"000", ErrorNeedleLength},
38 }
39 for _, tt := range testTable {
40 err := h.Add(tt.needleHex)
41 if err != tt.err {
42 t.Error(tt.needleHex, err.Error(), "!=", tt.err.Error())
43 }
44 }
45 })
46
47 t.Run("Get", func(t *testing.T) {
48 t.Parallel()
49 h := New()
50
51 // genNeedleHex returns a hex-encoded needle and its hash for a given index.
52 genNeedleHex := func(i int) (string, string) {
53 b := make([]byte, needle.PayloadLength)
54 b[0] = byte(i)
55 n, _ := needle.New(b)
56 return hex.EncodeToString(n.Bytes()), hex.EncodeToString(n.Hash())
57 }
58
59 // Add a valid needle to the haystack.
60 validNeedleHex, validHash := genNeedleHex(0)
61 h.Add(validNeedleHex)
62
63 // Add a needle and break the value type.
64 _, brokenHashValueType := genNeedleHex(1)
65 h.internal.Set(brokenHashValueType, 0)
66
67 // Add a needle with invalid hash.
68 _, invalidHash := genNeedleHex(2)
69 h.internal.Set(invalidHash, make([]byte, needle.PayloadLength))
70
71 testTable := []struct {
72 hash string
73 expected string
74 err error
75 }{
76 {validHash, validNeedleHex, nil},
77 {validHash[:len(validHash)-2], "", ErrorHashLength},
78 {validHash + "00", "", ErrorHashLength},
79 {"XXX" + validHash[3:], "", hex.InvalidByteError('X')},
80 {"bad" + validHash[3:], "", ErrorNeedleNotFound},
81 {brokenHashValueType, "", ErrorValueInvalidType},
82 {invalidHash, "", ErrorHashMismatch},
83 }
84 for _, tt := range testTable {
85 actual, err := h.Get(tt.hash)
86 if err != tt.err {
87 t.Error(tt.hash, err.Error(), "!=", tt.err.Error())
88 }
89 if actual != tt.expected {
90 t.Error(tt.hash, actual, "!=", tt.expected)
91 }
92 }
93 })
94}