-
Notifications
You must be signed in to change notification settings - Fork 1
/
journey_test.go
142 lines (107 loc) · 2.51 KB
/
journey_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package dht
import (
"fmt"
"net"
"testing"
"github.com/stretchr/testify/assert"
)
func TestJourneyAddRoutes(t *testing.T) {
target := randomID()
// test that nodes get added
j := newJourney(randomID(), target, 5)
nodes := []*node{
{id: randomID()},
{id: randomID()},
{id: randomID()},
{id: randomID()},
{id: randomID()},
}
j.add(nodes)
assert.Equal(t, target, j.destination)
assert.Equal(t, 5, j.remaining)
assert.Equal(t, 5, j.routes)
for i := 0; i < 5; i++ {
assert.NotNil(t, j.nodes[i])
assert.Greater(t, KEY_BITS, j.distances[i])
}
// test that we evict routes that are not
// closer than the new node we provide
j = newJourney(randomID(), target, 5)
// insert the maximum amount of nodes
nodes = make([]*node, K)
for i := 0; i < K; i++ {
nodes[i] = &node{
id: randomID(),
}
}
j.add(nodes)
// generate a node that will be a better match
var betterRoute *node
var betterDistance int
for {
id := randomID()
d := distance(id, target)
if d > j.distances[0] {
betterRoute = &node{id: id}
betterDistance = d
break
}
}
// add the new route, which should evict the worst one
j.add([]*node{betterRoute})
assert.Equal(t, betterRoute.id, j.nodes[0].id)
assert.Equal(t, betterDistance, j.distances[0])
}
func TestJourneyNextRoutes(t *testing.T) {
target := randomID()
// test that nodes are removed correctly
j := newJourney(randomID(), target, 5)
assert.Nil(t, j.next(5))
// insert the maximum amount of nodes
nodes := make([]*node, K)
for i := 0; i < K; i++ {
addr, _ := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.01:%d", 9000+i))
nodes[i] = &node{
id: randomID(),
address: addr,
}
}
j.add(nodes)
for i := 0; i < 4; i++ {
next := j.next(K / 4)
assert.Len(t, next, K/4)
assert.Equal(t, K-((K/4)*(i+1)), j.routes)
// TODO : check returned are best n routes
}
// test that maximum iteration limit
j = newJourney(randomID(), target, 1)
// insert the maximum amount of nodes
nodes = make([]*node, K)
for i := 0; i < K; i++ {
nodes[i] = &node{
id: randomID(),
}
}
j.add(nodes)
assert.NotNil(t, j.next(5))
assert.Nil(t, j.next(5))
}
func BenchmarkJourneyAddRoutes(b *testing.B) {
target := randomID()
j := newJourney(randomID(), target, 5)
nodes := make([][]*node, 10000)
for i := 0; i < 10000; i++ {
nodes[i] = []*node{
{id: randomID()},
{id: randomID()},
{id: randomID()},
{id: randomID()},
{id: randomID()},
}
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
j.add(nodes[i%1000])
}
}