github.com/lingyao2333/mo-zero@v1.4.1/core/stores/redis/redislock_test.go (about) 1 package redis 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 9 "github.com/lingyao2333/mo-zero/core/stringx" 10 ) 11 12 func TestRedisLock(t *testing.T) { 13 testFn := func(ctx context.Context) func(client *Redis) { 14 return func(client *Redis) { 15 key := stringx.Rand() 16 firstLock := NewRedisLock(client, key) 17 firstLock.SetExpire(5) 18 firstAcquire, err := firstLock.Acquire() 19 assert.Nil(t, err) 20 assert.True(t, firstAcquire) 21 22 secondLock := NewRedisLock(client, key) 23 secondLock.SetExpire(5) 24 againAcquire, err := secondLock.Acquire() 25 assert.Nil(t, err) 26 assert.False(t, againAcquire) 27 28 release, err := firstLock.Release() 29 assert.Nil(t, err) 30 assert.True(t, release) 31 32 endAcquire, err := secondLock.Acquire() 33 assert.Nil(t, err) 34 assert.True(t, endAcquire) 35 } 36 } 37 38 t.Run("normal", func(t *testing.T) { 39 runOnRedis(t, testFn(nil)) 40 }) 41 42 t.Run("withContext", func(t *testing.T) { 43 runOnRedis(t, testFn(context.Background())) 44 }) 45 } 46 47 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 }) 65 }