From 555f0d53b85bcee838d311c39c6301e7a7adcc3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Flc=E3=82=9B?= Date: Thu, 21 Dec 2023 14:47:31 +0800 Subject: [PATCH] test(crontab): redis mutex test case (#43) --- crontab/mutex/redis/mutex_test.go | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 crontab/mutex/redis/mutex_test.go diff --git a/crontab/mutex/redis/mutex_test.go b/crontab/mutex/redis/mutex_test.go new file mode 100644 index 0000000..5265e77 --- /dev/null +++ b/crontab/mutex/redis/mutex_test.go @@ -0,0 +1,38 @@ +package redis + +import ( + "context" + "testing" + "time" + + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/assert" + + "github.com/go-packagist/go-kratos-components/crontab" +) + +var ( + rdb = redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + }) + + ctx = context.Background() +) + +func TestMutex(t *testing.T) { + rdb.Ping(context.Background()) + m1 := New(rdb, WithExpired(time.Second*1)) + m2 := New(rdb, WithExpired(time.Second*1)) + + assert.NoError(t, m1.Lock(ctx, "test")) + assert.NoError(t, m1.Lock(ctx, "test")) + assert.EqualError(t, m2.Lock(ctx, "test"), crontab.ErrAnotherServerRunning.Error()) + + time.Sleep(time.Second * 2) + assert.NoError(t, m2.Lock(ctx, "test")) + assert.EqualError(t, m1.Lock(ctx, "test"), crontab.ErrAnotherServerRunning.Error()) + + assert.NoError(t, m2.Unlock(ctx, "test")) + assert.NoError(t, m1.Lock(ctx, "test")) + assert.EqualError(t, m2.Lock(ctx, "test"), crontab.ErrAnotherServerRunning.Error()) +}