-
Notifications
You must be signed in to change notification settings - Fork 0
/
locker_test.go
67 lines (50 loc) · 1.47 KB
/
locker_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
package redisx_test
import (
"testing"
"time"
"github.com/nyaruka/redisx"
"github.com/nyaruka/redisx/assertredis"
"github.com/stretchr/testify/assert"
)
func TestLocker(t *testing.T) {
rp := assertredis.TestDB()
rc := rp.Get()
defer rc.Close()
defer assertredis.FlushDB()
locker := redisx.NewLocker("test", time.Second*5)
// acquire a lock
lock1, err := locker.Grab(rp, time.Second)
assert.NoError(t, err)
assert.NotZero(t, lock1)
assertredis.Exists(t, rc, "test")
// try to acquire the same lock, should fail
lock2, err := locker.Grab(rp, time.Second)
assert.NoError(t, err)
assert.Zero(t, lock2)
// should succeed if we wait longer
lock3, err := locker.Grab(rp, time.Second*6)
assert.NoError(t, err)
assert.NotZero(t, lock3)
assert.NotEqual(t, lock1, lock3)
// extend the lock
err = locker.Extend(rp, lock3, time.Second*10)
assert.NoError(t, err)
// trying to grab it should fail with a 5 second timeout
lock4, err := locker.Grab(rp, time.Second*5)
assert.NoError(t, err)
assert.Zero(t, lock4)
// try to release the lock with wrong value
err = locker.Release(rp, "2352")
assert.NoError(t, err)
// no error but also dooesn't release the lock
assertredis.Exists(t, rc, "test")
// release the lock
err = locker.Release(rp, lock3)
assert.NoError(t, err)
assertredis.NotExists(t, rc, "test")
// new grab should work
lock5, err := locker.Grab(rp, time.Second*5)
assert.NoError(t, err)
assert.NotZero(t, lock5)
assertredis.Exists(t, rc, "test")
}