From 2510e0412d8326aae6e8ad548ba22c4a392b2f39 Mon Sep 17 00:00:00 2001 From: yxh Date: Wed, 9 Mar 2022 17:21:02 +0800 Subject: [PATCH] [fix bug] Fix redis cache adapter GetOrSetFunc, GetOrSetFuncLock method bug and add unit test --- os/gcache/gcache_adapter_redis.go | 4 +-- ...cache_z_unit_feature_adapter_redis_test.go | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/os/gcache/gcache_adapter_redis.go b/os/gcache/gcache_adapter_redis.go index 2ee71388a..30b0b56cd 100644 --- a/os/gcache/gcache_adapter_redis.go +++ b/os/gcache/gcache_adapter_redis.go @@ -189,7 +189,7 @@ func (c *AdapterRedis) GetOrSet(ctx context.Context, key interface{}, value inte if err != nil { return nil, err } - if result == nil { + if result.IsNil() { return gvar.New(value), c.Set(ctx, key, value, duration) } return @@ -207,7 +207,7 @@ func (c *AdapterRedis) GetOrSetFunc(ctx context.Context, key interface{}, f Func if err != nil { return nil, err } - if v == nil { + if v.IsNil() { value, err := f(ctx) if err != nil { return nil, err diff --git a/os/gcache/gcache_z_unit_feature_adapter_redis_test.go b/os/gcache/gcache_z_unit_feature_adapter_redis_test.go index b88500751..0ee7bb314 100644 --- a/os/gcache/gcache_z_unit_feature_adapter_redis_test.go +++ b/os/gcache/gcache_z_unit_feature_adapter_redis_test.go @@ -7,6 +7,7 @@ package gcache_test import ( + "context" "testing" "time" @@ -177,3 +178,35 @@ func Test_AdapterRedis_SetIfNotExist(t *testing.T) { t.Assert(d <= time.Second, true) }) } + +func Test_AdapterRedis_GetOrSetFunc(t *testing.T) { + defer cacheRedis.Clear(ctx) + gtest.C(t, func(t *gtest.T) { + var ( + key = "key" + value1 = "valueFunc" + ) + v, err := cacheRedis.GetOrSetFunc(ctx, key, func(ctx context.Context) (value interface{}, err error) { + value = value1 + return + }, 0) + t.AssertNil(err) + t.Assert(v, value1) + }) +} + +func Test_AdapterRedis_GetOrSetFuncLock(t *testing.T) { + defer cacheRedis.Clear(ctx) + gtest.C(t, func(t *gtest.T) { + var ( + key = "key" + value1 = "valueFuncLock" + ) + v, err := cacheRedis.GetOrSetFuncLock(ctx, key, func(ctx context.Context) (value interface{}, err error) { + value = value1 + return + }, time.Second*60) + t.AssertNil(err) + t.Assert(v, value1) + }) +}