-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocker_test.go
62 lines (49 loc) · 1.46 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
package locker
import (
"context"
"crypto/rand"
"io"
"strings"
"testing"
"time"
"github.com/go-redis/redis/v8"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
type ClientMock struct {
mock.Mock
}
func (m *ClientMock) EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *redis.Cmd {
arg := m.Called(append([]interface{}{ctx, sha1, keys}, args...)...)
return arg.Get(0).(*redis.Cmd)
}
func (m *ClientMock) Eval(ctx context.Context, script string, keys []string, args ...interface{}) *redis.Cmd {
return nil
}
func (m *ClientMock) ScriptExists(ctx context.Context, hashes ...string) *redis.BoolSliceCmd {
return nil
}
func (m *ClientMock) ScriptLoad(ctx context.Context, script string) *redis.StringCmd {
return nil
}
func TestLocker(t *testing.T) {
randReader := rand.Reader
rand.Reader = strings.NewReader("qwertyqwertyqwer")
defer func() {
rand.Reader = randReader
}()
clientMock := &ClientMock{}
locker := NewLocker(clientMock)
ctx := context.Background()
key := "key"
ttl := 500 * time.Millisecond
value := "cXdlcnR5cXdlcnR5cXdlcg=="
keys := []string{key}
clientMock.On("EvalSha", ctx, lockscr.Hash(), keys, value, int(ttl/time.Millisecond)).Return(redis.NewCmdResult(interface{}(int64(-3)), nil))
r, err := locker.Lock(ctx, key, ttl)
require.NoError(t, err)
require.Equal(t, value, r.value)
clientMock.AssertExpectations(t)
_, err = locker.Lock(ctx, key, ttl)
require.Equal(t, io.EOF, err)
}