Skip to content
File

Blob: spec/chord/chord_test.go

go123 lines
1package chord
2 
3import (
4 "fmt"
5 "testing"
6 "time"
7 
8 "go.miragespace.co/specter/spec/protocol"
9 
10 "github.com/stretchr/testify/require"
11)
12 
13// func TestHash(t *testing.T) {
14// as := require.New(t)
15 
16// b := []byte("test key")
17// as.Equal(wyhash.Sum64(MaxIdentitifer, b)%MaxIdentitifer, Hash(b))
18// }
19 
20func TestModulo(t *testing.T) {
21 var (
22 as = require.New(t)
23 x uint64 = 1 << 24
24 y uint64 = 1 << 28
25 )
26 
27 as.Equal((x+y)%MaxIdentitifer, ModuloSum(x, y))
28}
29 
30func TestRandom(t *testing.T) {
31 as := require.New(t)
32 
33 t1 := Random()
34 time.Sleep(time.Second)
35 t2 := Random()
36 
37 as.NotEqual(t1, t2)
38}
39 
40func TestBetweenExclusive(t *testing.T) {
41 tables := []struct {
42 low uint64
43 target uint64
44 high uint64
45 result bool
46 }{
47 {
48 low: 10,
49 target: 20,
50 high: 10,
51 result: true,
52 },
53 {
54 low: 10,
55 target: 10,
56 high: 20,
57 result: false,
58 },
59 {
60 low: 20,
61 target: 10,
62 high: 10,
63 result: false,
64 },
65 }
66 
67 for _, table := range tables {
68 t.Run(fmt.Sprintf("%d ∈ (%d, %d) == %v", table.target, table.low, table.high, table.result), func(t *testing.T) {
69 as := require.New(t)
70 as.Condition(func() (success bool) {
71 return table.result == Between(table.low, table.target, table.high, false)
72 })
73 })
74 }
75}
76 
77type fakeNode struct {
78 VNode
79 identity *protocol.Node
80}
81 
82func (f *fakeNode) ID() uint64 {
83 return f.identity.GetId()
84}
85 
86func (f *fakeNode) Identity() *protocol.Node {
87 return f.identity
88}
89 
90func TestSuccListNoDuplicateByID(t *testing.T) {
91 as := require.New(t)
92 
93 nodes := []VNode{
94 &fakeNode{nil, &protocol.Node{Id: 2}},
95 &fakeNode{nil, &protocol.Node{Id: 2}},
96 &fakeNode{nil, &protocol.Node{Id: 2}},
97 &fakeNode{nil, &protocol.Node{Id: 3}},
98 &fakeNode{nil, &protocol.Node{Id: 4}},
99 }
100 immediate := &fakeNode{nil, &protocol.Node{Id: 1}}
101 
102 list := MakeSuccListByID(immediate, nodes, 3)
103 as.Len(list, 3)
104 as.Equal(uint64(1), list[0].ID())
105}
106 
107func TestSuccListNoDuplicateByAddress(t *testing.T) {
108 as := require.New(t)
109 
110 nodes := []VNode{
111 &fakeNode{nil, &protocol.Node{Address: "127.0.0.2"}},
112 &fakeNode{nil, &protocol.Node{Address: "127.0.0.2"}},
113 &fakeNode{nil, &protocol.Node{Address: "127.0.0.2"}},
114 &fakeNode{nil, &protocol.Node{Address: "127.0.0.3"}},
115 &fakeNode{nil, &protocol.Node{Address: "127.0.0.4"}},
116 }
117 immediate := &fakeNode{nil, &protocol.Node{Address: "127.0.0.1"}}
118 
119 list := MakeSuccListByAddress(immediate, nodes, 3)
120 as.Len(list, 3)
121 as.Equal("127.0.0.1", list[0].Identity().GetAddress())
122}