github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/lock/redis/lock_test.go (about)

     1  package redislock
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/alicebob/miniredis/v2"
     9  	"github.com/go-redis/redis/v8"
    10  	"github.com/stretchr/testify/suite"
    11  )
    12  
    13  type RedisLockTestSuite struct {
    14  	suite.Suite
    15  
    16  	cli *redis.Client
    17  }
    18  
    19  func (s *RedisLockTestSuite) SetupTest() {
    20  	s.cli.FlushAll(context.Background())
    21  }
    22  
    23  func (s *RedisLockTestSuite) TearDownTest() {
    24  	s.cli.FlushAll(context.Background())
    25  }
    26  
    27  func (s *RedisLockTestSuite) TestMutex() {
    28  	_, err := New(s.cli, "", time.Second, time.Second)
    29  	s.Error(err)
    30  	l, err := New(s.cli, "test", time.Second, time.Second)
    31  	s.NoError(err)
    32  
    33  	ctx := context.Background()
    34  	ctx, err = l.Lock(ctx)
    35  	s.Nil(ctx.Err())
    36  	s.NoError(err)
    37  
    38  	err = l.Unlock(ctx)
    39  	s.NoError(err)
    40  }
    41  
    42  func (s *RedisLockTestSuite) TestTryLock() {
    43  	l1, err := New(s.cli, "test", time.Second, time.Second)
    44  	s.NoError(err)
    45  	l2, err := New(s.cli, "test", time.Second, time.Second)
    46  	s.NoError(err)
    47  
    48  	ctx1, err := l1.Lock(context.Background())
    49  	s.Nil(ctx1.Err())
    50  	s.NoError(err)
    51  
    52  	ctx2, err := l2.TryLock(context.Background())
    53  	s.Nil(ctx2)
    54  	s.Error(err)
    55  }
    56  
    57  func TestRedisLock(t *testing.T) {
    58  	s, err := miniredis.Run()
    59  	if err != nil {
    60  		t.Fail()
    61  	}
    62  	defer s.Close()
    63  
    64  	cli := redis.NewClient(&redis.Options{
    65  		Addr: s.Addr(),
    66  		DB:   0,
    67  	})
    68  	defer cli.Close()
    69  	suite.Run(t, &RedisLockTestSuite{
    70  		cli: cli,
    71  	})
    72  }