redislock_test.go 1.1 KB

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