haystack_test.gno

1.48 Kb ยท 69 lines
 1package haystack
 2
 3import (
 4	"encoding/hex"
 5	"testing"
 6
 7	"gno.land/p/demo/testutils"
 8	"gno.land/p/demo/urequire"
 9	"gno.land/p/n2p5/haystack"
10	"gno.land/p/n2p5/haystack/needle"
11)
12
13func TestHaystack(t *testing.T) {
14	t.Parallel()
15	// needleHex returns a hex-encoded needle and its hash for a given index.
16	genNeedleHex := func(i int) (string, string) {
17		b := make([]byte, needle.PayloadLength)
18		b[0] = byte(i)
19		n, _ := needle.New(b)
20		return hex.EncodeToString(n.Bytes()), hex.EncodeToString(n.Hash())
21	}
22
23	u1 := testutils.TestAddress("u1")
24	u2 := testutils.TestAddress("u2")
25
26	t.Run("Add", func(t *testing.T) {
27		t.Parallel()
28
29		n1, _ := genNeedleHex(1)
30		n2, _ := genNeedleHex(2)
31		n3, _ := genNeedleHex(3)
32
33		testing.SetOriginCaller(u1)
34		urequire.NotPanics(t, func() { Add(n1) })
35		urequire.PanicsWithMessage(t,
36			haystack.ErrorDuplicateNeedle.Error(),
37			func() {
38				Add(n1)
39			})
40		testing.SetOriginCaller(u2)
41		urequire.NotPanics(t, func() { Add(n2) })
42		urequire.NotPanics(t, func() { Add(n3) })
43	})
44
45	t.Run("Get", func(t *testing.T) {
46		t.Parallel()
47
48		n1, h1 := genNeedleHex(4)
49		_, h2 := genNeedleHex(5)
50
51		testing.SetOriginCaller(u1)
52		urequire.NotPanics(t, func() { Add(n1) })
53		urequire.NotPanics(t, func() {
54			result := Get(h1)
55			urequire.Equal(t, n1, result)
56		})
57
58		testing.SetOriginCaller(u2)
59		urequire.NotPanics(t, func() {
60			result := Get(h1)
61			urequire.Equal(t, n1, result)
62		})
63		urequire.PanicsWithMessage(t,
64			haystack.ErrorNeedleNotFound.Error(),
65			func() {
66				Get(h2)
67			})
68	})
69}