@@ -3,12 +3,45 @@ package redis
3
3
import (
4
4
"context"
5
5
"testing"
6
+ "time"
6
7
8
+ "github.com/alicebob/miniredis/v2"
7
9
"github.com/stretchr/testify/assert"
8
10
9
11
"github.com/zeromicro/go-zero/core/stringx"
10
12
)
11
13
14
+ func TestRedisLock_SameAcquire (t * testing.T ) {
15
+
16
+ var (
17
+ s = miniredis .RunT (t )
18
+ seconds = 5
19
+ )
20
+ client := MustNewRedis (
21
+ RedisConf {
22
+ Host : s .Addr (),
23
+ Type : NodeType ,
24
+ },
25
+ )
26
+
27
+ key := stringx .Rand ()
28
+ firstLock := NewRedisLock (client , key )
29
+ firstLock .SetExpire (seconds )
30
+ firstAcquire , err := firstLock .Acquire ()
31
+ assert .Nil (t , err )
32
+ assert .True (t , firstAcquire )
33
+
34
+ secondAcquire , err := firstLock .Acquire ()
35
+ assert .Nil (t , err )
36
+ assert .False (t , secondAcquire )
37
+
38
+ s .FastForward (time .Second * time .Duration (seconds + 1 ))
39
+
40
+ thirdAcquire , err := firstLock .Acquire ()
41
+ assert .Nil (t , err )
42
+ assert .True (t , thirdAcquire )
43
+ }
44
+
12
45
func TestRedisLock (t * testing.T ) {
13
46
testFn := func (ctx context.Context ) func (client * Redis ) {
14
47
return func (client * Redis ) {
@@ -35,31 +68,39 @@ func TestRedisLock(t *testing.T) {
35
68
}
36
69
}
37
70
38
- t .Run ("normal" , func (t * testing.T ) {
39
- runOnRedis (t , testFn (nil ))
40
- })
71
+ t .Run (
72
+ "normal" , func (t * testing.T ) {
73
+ runOnRedis (t , testFn (nil ))
74
+ },
75
+ )
41
76
42
- t .Run ("withContext" , func (t * testing.T ) {
43
- runOnRedis (t , testFn (context .Background ()))
44
- })
77
+ t .Run (
78
+ "withContext" , func (t * testing.T ) {
79
+ runOnRedis (t , testFn (context .Background ()))
80
+ },
81
+ )
45
82
}
46
83
47
84
func TestRedisLock_Expired (t * testing.T ) {
48
- runOnRedis (t , func (client * Redis ) {
49
- key := stringx .Rand ()
50
- redisLock := NewRedisLock (client , key )
51
- ctx , cancel := context .WithCancel (context .Background ())
52
- cancel ()
53
- _ , err := redisLock .AcquireCtx (ctx )
54
- assert .NotNil (t , err )
55
- })
56
-
57
- runOnRedis (t , func (client * Redis ) {
58
- key := stringx .Rand ()
59
- redisLock := NewRedisLock (client , key )
60
- ctx , cancel := context .WithCancel (context .Background ())
61
- cancel ()
62
- _ , err := redisLock .ReleaseCtx (ctx )
63
- assert .NotNil (t , err )
64
- })
85
+ runOnRedis (
86
+ t , func (client * Redis ) {
87
+ key := stringx .Rand ()
88
+ redisLock := NewRedisLock (client , key )
89
+ ctx , cancel := context .WithCancel (context .Background ())
90
+ cancel ()
91
+ _ , err := redisLock .AcquireCtx (ctx )
92
+ assert .NotNil (t , err )
93
+ },
94
+ )
95
+
96
+ runOnRedis (
97
+ t , func (client * Redis ) {
98
+ key := stringx .Rand ()
99
+ redisLock := NewRedisLock (client , key )
100
+ ctx , cancel := context .WithCancel (context .Background ())
101
+ cancel ()
102
+ _ , err := redisLock .ReleaseCtx (ctx )
103
+ assert .NotNil (t , err )
104
+ },
105
+ )
65
106
}
0 commit comments