-
Notifications
You must be signed in to change notification settings - Fork 6
/
lease_test.go
81 lines (73 loc) · 2.32 KB
/
lease_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
package main
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"inet.af/netaddr"
)
func TestFileLeaseManager_createOrUpdatePeer(t *testing.T) {
ipPrefix := netaddr.MustParseIPPrefix("10.90.0.1/20")
lm := &fileLeaseManager{
wgRecords: map[string]WGRecord{},
ipPrefix: ipPrefix,
}
testPubKey1 := "k1a1fEw+lqB/JR1pKjI597R54xzfP9Kxv4M7hufyNAY="
testPubKey2 := "E1gSkv2jS/P+p8YYmvm7ByEvwpLPqQBdx70SPtNSwCo="
testUsername := "test@example.com"
testExpiry := time.Unix(0, 0)
// Test that lm.ip is skipped
record, err := lm.createOrUpdatePeer(testUsername, testPubKey1, testExpiry)
if err != nil {
t.Fatal(err)
}
if record.IP.Compare(netaddr.MustParseIP("10.90.0.2")) != 0 {
t.Fatalf("Unexpected IP returned %s", record.IP.String())
}
assert.Equal(t, 1, len(lm.wgRecords))
assert.Equal(t, testPubKey1, lm.wgRecords[testUsername].PubKey)
// Test that same username with different public key will replace the
// existing record, instead of adding a new one and return the same address
record2, err := lm.createOrUpdatePeer(testUsername, testPubKey2, testExpiry)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, 1, len(lm.wgRecords))
assert.Equal(t, testPubKey2, lm.wgRecords[testUsername].PubKey)
if record.IP.Compare(record2.IP) != 0 {
t.Fatalf("Expected the same ip address for the same user, got %v", record2.IP)
}
// Test that empty username will error
_, err = lm.createOrUpdatePeer("", testPubKey2, testExpiry)
assert.Equal(t, err, fmt.Errorf("Cannot add peer for empty username"))
}
func TestGetAvailableIPAddresses(t *testing.T) {
ipPrefix := netaddr.MustParseIPPrefix("10.90.0.1/20")
r1 := WGRecord{
PubKey: "k1a1fEw+lqB/JR1pKjI597R54xzfP9Kxv4M7hufyNAY=",
IP: netaddr.MustParseIP("10.90.0.2"),
expires: time.Unix(0, 0)}
r2 := WGRecord{
PubKey: "E1gSkv2jS/P+p8YYmvm7ByEvwpLPqQBdx70SPtNSwCo=",
IP: netaddr.MustParseIP("10.90.0.4"),
expires: time.Unix(0, 0)}
lm := &fileLeaseManager{
wgRecords: map[string]WGRecord{"r1": r1, "r2": r2},
ipPrefix: ipPrefix,
}
testCases := []struct {
t fileLeaseManager
e netaddr.IP
}{
{
t: *lm,
e: netaddr.IPv4(10, 90, 0, 3),
},
}
for _, test := range testCases {
a := test.t.nextAvailableAddress()
if a.Compare(test.e) != 0 {
t.Errorf("getNextAvailableAddress: expected=%s got=%s", test.e.String(), a.String())
}
}
}