github.com/binbinly/pkg@v0.0.11-0.20240321014439-f4fbf666eb0f/lock/lock_test.go (about)

     1  package lock
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	redis2 "github.com/binbinly/pkg/storage/redis"
     9  	"github.com/redis/go-redis/v9"
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  var Client *redis.Client
    14  
    15  func TestMain(m *testing.M) {
    16  	Client = redis2.InitTestRedis()
    17  	if code := m.Run(); code != 0 {
    18  		panic(code)
    19  	}
    20  }
    21  
    22  func TestLockWithDefaultTimeout(t *testing.T) {
    23  	lock := NewRedisLock(Client, "lock1", WithTTL(2*time.Second))
    24  	ok, err := lock.Lock(context.Background())
    25  	assert.Nil(t, err)
    26  	assert.True(t, ok)
    27  
    28  	ok, err = lock.Unlock(context.Background())
    29  	assert.Nil(t, err)
    30  	assert.True(t, ok)
    31  }
    32  
    33  func TestLockWithTimeout(t *testing.T) {
    34  	t.Run("should lock/unlock success", func(t *testing.T) {
    35  		ctx := context.Background()
    36  		lock1 := NewRedisLock(Client, "lock2", WithTTL(2*time.Second))
    37  		ok, err := lock1.Lock(ctx)
    38  		assert.Nil(t, err)
    39  		assert.True(t, ok)
    40  
    41  		ok, err = lock1.Unlock(ctx)
    42  		assert.Nil(t, err)
    43  		assert.True(t, ok)
    44  	})
    45  
    46  	t.Run("should unlock failed", func(t *testing.T) {
    47  		ctx := context.Background()
    48  		lock2 := NewRedisLock(Client, "lock3", WithTTL(2*time.Second))
    49  		ok, err := lock2.Lock(ctx)
    50  		assert.Nil(t, err)
    51  		assert.True(t, ok)
    52  
    53  		time.Sleep(3 * time.Second)
    54  
    55  		ok, err = lock2.Unlock(ctx)
    56  		assert.Nil(t, err)
    57  		//assert.False(t, ok)
    58  	})
    59  }