-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis_test.go
89 lines (78 loc) · 1.66 KB
/
redis_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
package redlock
import (
"os"
"testing"
"time"
"github.com/go-redis/redis"
)
func newRedisMutex(t *testing.T, key, redisURL string) *Mutex {
t.Helper()
o, err := redis.ParseURL(redisURL)
if err != nil {
t.Fatalf("failed to ParseURL(%s): %s", redisURL, err)
}
c := redis.NewClient(o)
return NewWithRedis(key, c)
}
func localRedisURL(t *testing.T) string {
t.Helper()
u := os.Getenv("TEST_REDIS_URL")
if u != "" {
t.Logf("using redis on %s", u)
return u
}
return "redis://127.0.0.1:6379/0"
}
func newLocalRedisMutex(t *testing.T, key string, n int) []*Mutex {
t.Helper()
u := localRedisURL(t)
r := make([]*Mutex, n)
for i := 0; i < n; i++ {
r[i] = newRedisMutex(t, key, u)
}
return r
}
func TestSingleLock(t *testing.T) {
m := newLocalRedisMutex(t, "Lock", 2)
err := m[0].Lock()
if err != nil {
t.Fatalf("lock#1 failed: %s", err)
}
defer m[0].Unlock()
err = m[1].Lock()
if err != ErrGaveUpLock {
t.Fatalf("lock#2 unexpected: %s", err)
}
}
func TestSingleUnlock(t *testing.T) {
m := newLocalRedisMutex(t, "Unlock", 2)
err := m[0].Lock()
if err != nil {
t.Fatalf("lock#1 failed: %s", err)
}
m[0].Unlock()
err = m[1].Lock()
if err != nil {
t.Fatalf("lock#2 failed: %s", err)
}
m[1].Unlock()
}
func TestSingleExpire(t *testing.T) {
m := newLocalRedisMutex(t, "Expire", 2)
m[0].SetExpiration(500 * time.Millisecond)
err := m[0].Lock()
if err != nil {
t.Fatalf("lock#1 failed: %s", err)
}
defer m[0].Unlock()
err = m[1].Lock()
if err != ErrGaveUpLock {
t.Fatalf("lock#2-1 unexpected: %s", err)
}
time.Sleep(1000 * time.Millisecond)
err = m[1].Lock()
if err != nil {
t.Fatalf("lock#2-2 failed: %s", err)
}
m[1].Unlock()
}