-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo_test.go
93 lines (89 loc) · 2.07 KB
/
demo_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
package redisLock
import (
"context"
"errors"
"github.com/golang/mock/gomock"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/assert"
"lock/Lock"
"lock/mocks"
"testing"
"time"
)
func TestName(t *testing.T) {
}
// 单元测试
func TestClient_TryLock(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
testCases := []struct {
//测试场景
name string
//输入
key string
expiration time.Duration
//设置mock数据
mock func() redis.Cmdable
//预期输出 测试方法返回值
wantErr error
wantLock *Lock.Lock
}{
//成功案例
{
name: "locked",
key: "locked-key",
expiration: time.Minute,
mock: func() redis.Cmdable {
rdb := mocks.NewMockCmdable(ctrl)
res := redis.NewBoolResult(true, nil)
rdb.EXPECT().SetNX(gomock.Any(), "locked-key", gomock.Any(), time.Minute).
Return(res)
return rdb
},
wantLock: &Lock.Lock{
Key: "locked-key",
},
},
//网络错误
{
name: "network",
key: "network-key",
expiration: time.Minute,
mock: func() redis.Cmdable {
rdb := mocks.NewMockCmdable(ctrl)
res := redis.NewBoolResult(false, errors.New("network error"))
rdb.EXPECT().SetNX(gomock.Any(), "network-key", gomock.Any(), time.Minute).
Return(res)
return rdb
},
wantErr: errors.New("network error"),
},
//redis被手动删除
{
name: "failed to lock",
key: "failed-key",
expiration: time.Minute,
mock: func() redis.Cmdable {
rdb := mocks.NewMockCmdable(ctrl)
res := redis.NewBoolResult(false, nil)
rdb.EXPECT().
SetNX(gomock.Any(), "failed-key", gomock.Any(), time.Minute).
Return(res)
return rdb
},
wantErr: Lock.ErrFailedTOPreemptLock,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
c := Lock.NewClient(tc.mock())
l, err := c.TryLock(context.Background(), tc.key, tc.expiration)
assert.Equal(t, tc.wantErr, err)
if err != nil {
return
}
assert.Equal(t, tc.wantLock.Key, l.Key)
assert.NotEmpty(t, l.Value)
})
}
}