-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
tokens_test.go
54 lines (51 loc) · 1.26 KB
/
tokens_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
package dht
import (
"net"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestTokenServer(t *testing.T) {
addr1 := NewAddr(&net.UDPAddr{
IP: []byte{1, 2, 3, 4},
})
addr2 := NewAddr(&net.UDPAddr{
IP: []byte{1, 2, 3, 3},
})
ts := tokenServer{
secret: []byte("42"),
interval: 5 * time.Minute,
maxIntervalDelta: 2,
}
tok := ts.CreateToken(addr1)
assert.Len(t, tok, 20)
assert.True(t, ts.ValidToken(tok, addr1))
assert.False(t, ts.ValidToken(tok[1:], addr1))
assert.False(t, ts.ValidToken(tok, addr2))
func() {
ts0 := ts
ts0.secret = nil
assert.False(t, ts0.ValidToken(tok, addr1))
}()
now := time.Now()
setTime := func(t time.Time) {
ts.timeNow = func() time.Time {
return t
}
}
setTime(now)
tok = ts.CreateToken(addr1)
assert.True(t, ts.ValidToken(tok, addr1))
setTime(time.Time{})
assert.False(t, ts.ValidToken(tok, addr1))
setTime(now.Add(-5 * time.Minute))
assert.False(t, ts.ValidToken(tok, addr1))
setTime(now)
assert.True(t, ts.ValidToken(tok, addr1))
setTime(now.Add(5 * time.Minute))
assert.True(t, ts.ValidToken(tok, addr1))
setTime(now.Add(2 * 5 * time.Minute))
assert.True(t, ts.ValidToken(tok, addr1))
setTime(now.Add(3 * 5 * time.Minute))
assert.False(t, ts.ValidToken(tok, addr1))
}