github.com/wfusion/gofusion@v1.1.14/test/lock/cases/expired_test.go (about)

     1  package cases
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/suite"
     9  
    10  	"github.com/wfusion/gofusion/lock"
    11  	"github.com/wfusion/gofusion/log"
    12  
    13  	testLock "github.com/wfusion/gofusion/test/lock"
    14  )
    15  
    16  func TestExpired(t *testing.T) {
    17  	testingSuite := &Expired{Test: new(testLock.Test)}
    18  	testingSuite.Init(testingSuite)
    19  	suite.Run(t, testingSuite)
    20  }
    21  
    22  type Expired struct {
    23  	*testLock.Test
    24  }
    25  
    26  func (t *Expired) BeforeTest(suiteName, testName string) {
    27  	t.Catch(func() {
    28  		log.Info(context.Background(), "right before %s %s", suiteName, testName)
    29  	})
    30  }
    31  
    32  func (t *Expired) AfterTest(suiteName, testName string) {
    33  	t.Catch(func() {
    34  		log.Info(context.Background(), "right after %s %s", suiteName, testName)
    35  	})
    36  }
    37  
    38  func (t *Expired) TestRedisLua() {
    39  	t.Catch(func() {
    40  		locker := lock.Use("redis_lua", lock.AppName(t.AppName()))
    41  		key := "redis_lua_lock_expired_key"
    42  		t.testExpired(locker, key, 100*time.Millisecond, time.Second)
    43  	})
    44  }
    45  
    46  func (t *Expired) TestRedisNx() {
    47  	t.Catch(func() {
    48  		locker := lock.Use("redis_nx", lock.AppName(t.AppName()))
    49  		key := "redis_nx_lock_expired_key"
    50  		t.testExpired(locker, key, 100*time.Millisecond, 500*time.Millisecond)
    51  	})
    52  }
    53  
    54  func (t *Expired) TestMySQL() {
    55  	t.Catch(func() {
    56  		locker := lock.Use("mysql", lock.AppName(t.AppName()))
    57  		key := "mysql_lock_expired_key"
    58  		t.testExpired(locker, key, 100*time.Millisecond, 500*time.Millisecond)
    59  	})
    60  }
    61  
    62  func (t *Expired) TestMongo() {
    63  	t.Catch(func() {
    64  		locker := lock.Use("mongo", lock.AppName(t.AppName()))
    65  		key := "mongo_lock_expired_key"
    66  		t.testExpired(locker, key, 100*time.Millisecond, 2*time.Second)
    67  	})
    68  }
    69  
    70  func (t *Expired) testExpired(locker lock.Lockable, key string, expired time.Duration, waitTime time.Duration) {
    71  	t.Catch(func() {
    72  		ctx := context.Background()
    73  		for i := 0; i < 5; i++ {
    74  			err := locker.Lock(ctx, key, lock.Expire(expired))
    75  			if err != nil {
    76  				t.FailNow("try to lock failed", err)
    77  			}
    78  			time.Sleep(waitTime)
    79  		}
    80  	})
    81  }