forked from ryandotsmith/redisync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex_test.go
110 lines (98 loc) · 1.93 KB
/
mutex_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
package redisync
import (
"github.com/gomodule/redigo/redis"
"net/url"
"os"
"testing"
"time"
)
func newConn() (redis.Conn, error) {
redisUrl, err := url.Parse(os.Getenv("REDIS_URL"))
if err != nil {
return nil, err
}
c, err := redis.Dial("tcp", redisUrl.Host)
if err != nil {
return nil, err
}
return c, nil
}
func TestLock(t *testing.T) {
rc, err := newConn()
if err != nil {
t.Error(err)
t.FailNow()
}
defer rc.Close()
ttl := time.Second
m := NewMutex("redisync.test.1", ttl)
m.Lock(rc)
time.Sleep(ttl)
ok := m.TryLock(rc)
if !ok {
t.Error("Expected mutex to be lockable.")
t.FailNow()
}
m.Unlock(rc)
}
func TestLockLocked(t *testing.T) {
rc, err := newConn()
if err != nil {
t.Error(err)
t.FailNow()
}
defer rc.Close()
ttl := time.Second
m1 := NewMutex("redisync.test.1", ttl)
if ok := m1.TryLock(rc); !ok {
t.Error("Expected mutex to be lockable.")
t.FailNow()
}
m2 := NewMutex("redisync.test.1", ttl)
if ok := m2.TryLock(rc); ok {
t.Error("Expected mutex not to be lockable.")
t.FailNow()
}
m1.Unlock(rc)
}
func TestUnlockOtherLocked(t *testing.T) {
rc, err := newConn()
if err != nil {
t.Error(err)
t.FailNow()
}
defer rc.Close()
ttl := time.Second
m1 := NewMutex("redisync.test.1", ttl)
if ok := m1.TryLock(rc); !ok {
t.Error("Expected mutex to be lockable.")
t.FailNow()
}
m2 := NewMutex("redisync.test.1", ttl)
if ok, _ := m2.Unlock(rc); ok {
t.Error("Expected mutex not to be unlockable.")
t.FailNow()
}
m1.Unlock(rc)
}
func TestLockExpired(t *testing.T) {
rc, err := newConn()
if err != nil {
t.Error(err)
t.FailNow()
}
defer rc.Close()
ttl := time.Second
m1 := NewMutex("redisync.test.1", ttl)
if ok := m1.TryLock(rc); !ok {
t.Error("Expected mutex to be lockable.")
t.FailNow()
}
time.Sleep(ttl)
m2 := NewMutex("redisync.test.1", ttl)
if ok := m2.TryLock(rc); !ok {
t.Error("Expected mutex to be lockable.")
t.FailNow()
}
m2.Unlock(rc)
}