refine tests

master
kevin 4 years ago
parent 677d581bd1
commit b004b070d7

@ -2,20 +2,16 @@ package bloom
import ( import (
"testing" "testing"
"time"
"github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/lang" "github.com/tal-tech/go-zero/core/stores/redistest"
"github.com/tal-tech/go-zero/core/stores/redis"
) )
func TestRedisBitSet_New_Set_Test(t *testing.T) { func TestRedisBitSet_New_Set_Test(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
store := redis.NewRedis(s.Addr(), redis.NodeType)
bitSet := newRedisBitSet(store, "test_key", 1024) bitSet := newRedisBitSet(store, "test_key", 1024)
isSetBefore, err := bitSet.check([]uint{0}) isSetBefore, err := bitSet.check([]uint{0})
if err != nil { if err != nil {
@ -46,11 +42,10 @@ func TestRedisBitSet_New_Set_Test(t *testing.T) {
} }
func TestRedisBitSet_Add(t *testing.T) { func TestRedisBitSet_Add(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
store := redis.NewRedis(s.Addr(), redis.NodeType)
filter := New(store, "test_key", 64) filter := New(store, "test_key", 64)
assert.Nil(t, filter.Add([]byte("hello"))) assert.Nil(t, filter.Add([]byte("hello")))
assert.Nil(t, filter.Add([]byte("world"))) assert.Nil(t, filter.Add([]byte("world")))
@ -58,22 +53,3 @@ func TestRedisBitSet_Add(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.True(t, ok) assert.True(t, ok)
} }
func createMiniRedis() (r *miniredis.Miniredis, clean func(), err error) {
r, err = miniredis.Run()
if err != nil {
return nil, nil, err
}
return r, func() {
ch := make(chan lang.PlaceholderType)
go func() {
r.Close()
close(ch)
}()
select {
case <-ch:
case <-time.After(time.Second):
}
}, nil
}

@ -6,6 +6,7 @@ import (
"github.com/alicebob/miniredis" "github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redistest"
) )
func TestPeriodLimit_Take(t *testing.T) { func TestPeriodLimit_Take(t *testing.T) {
@ -33,16 +34,16 @@ func TestPeriodLimit_RedisUnavailable(t *testing.T) {
} }
func testPeriodLimit(t *testing.T, opts ...LimitOption) { func testPeriodLimit(t *testing.T, opts ...LimitOption) {
s, err := miniredis.Run() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer s.Close() defer clean()
const ( const (
seconds = 1 seconds = 1
total = 100 total = 100
quota = 5 quota = 5
) )
l := NewPeriodLimit(seconds, quota, redis.NewRedis(s.Addr(), redis.NodeType), "periodlimit", opts...) l := NewPeriodLimit(seconds, quota, store, "periodlimit", opts...)
var allowed, hitQuota, overQuota int var allowed, hitQuota, overQuota int
for i := 0; i < total; i++ { for i := 0; i < total; i++ {
val, err := l.Take("first") val, err := l.Take("first")

@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redistest"
) )
func init() { func init() {
@ -44,16 +45,16 @@ func TestTokenLimit_Rescue(t *testing.T) {
} }
func TestTokenLimit_Take(t *testing.T) { func TestTokenLimit_Take(t *testing.T) {
s, err := miniredis.Run() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer s.Close() defer clean()
const ( const (
total = 100 total = 100
rate = 5 rate = 5
burst = 10 burst = 10
) )
l := NewTokenLimiter(rate, burst, redis.NewRedis(s.Addr(), redis.NodeType), "tokenlimit") l := NewTokenLimiter(rate, burst, store, "tokenlimit")
var allowed int var allowed int
for i := 0; i < total; i++ { for i := 0; i < total; i++ {
time.Sleep(time.Second / time.Duration(total)) time.Sleep(time.Second / time.Duration(total))
@ -66,16 +67,16 @@ func TestTokenLimit_Take(t *testing.T) {
} }
func TestTokenLimit_TakeBurst(t *testing.T) { func TestTokenLimit_TakeBurst(t *testing.T) {
s, err := miniredis.Run() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer s.Close() defer clean()
const ( const (
total = 100 total = 100
rate = 5 rate = 5
burst = 10 burst = 10
) )
l := NewTokenLimiter(rate, burst, redis.NewRedis(s.Addr(), redis.NodeType), "tokenlimit") l := NewTokenLimiter(rate, burst, store, "tokenlimit")
var allowed int var allowed int
for i := 0; i < total; i++ { for i := 0; i < total; i++ {
if l.Allow() { if l.Allow() {

@ -12,6 +12,7 @@ import (
"github.com/tal-tech/go-zero/core/errorx" "github.com/tal-tech/go-zero/core/errorx"
"github.com/tal-tech/go-zero/core/hash" "github.com/tal-tech/go-zero/core/hash"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redistest"
"github.com/tal-tech/go-zero/core/syncx" "github.com/tal-tech/go-zero/core/syncx"
) )
@ -75,23 +76,23 @@ func (mc *mockedNode) TakeWithExpire(v interface{}, key string, query func(v int
func TestCache_SetDel(t *testing.T) { func TestCache_SetDel(t *testing.T) {
const total = 1000 const total = 1000
r1, clean1, err := createMiniRedis() r1, clean1, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean1() defer clean1()
r2, clean2, err := createMiniRedis() r2, clean2, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean2() defer clean2()
conf := ClusterConf{ conf := ClusterConf{
{ {
RedisConf: redis.RedisConf{ RedisConf: redis.RedisConf{
Host: r1.Addr(), Host: r1.Addr,
Type: redis.NodeType, Type: redis.NodeType,
}, },
Weight: 100, Weight: 100,
}, },
{ {
RedisConf: redis.RedisConf{ RedisConf: redis.RedisConf{
Host: r2.Addr(), Host: r2.Addr,
Type: redis.NodeType, Type: redis.NodeType,
}, },
Weight: 100, Weight: 100,
@ -123,13 +124,13 @@ func TestCache_SetDel(t *testing.T) {
func TestCache_OneNode(t *testing.T) { func TestCache_OneNode(t *testing.T) {
const total = 1000 const total = 1000
r, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
conf := ClusterConf{ conf := ClusterConf{
{ {
RedisConf: redis.RedisConf{ RedisConf: redis.RedisConf{
Host: r.Addr(), Host: r.Addr,
Type: redis.NodeType, Type: redis.NodeType,
}, },
Weight: 100, Weight: 100,

@ -15,6 +15,7 @@ import (
"github.com/tal-tech/go-zero/core/mathx" "github.com/tal-tech/go-zero/core/mathx"
"github.com/tal-tech/go-zero/core/stat" "github.com/tal-tech/go-zero/core/stat"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redistest"
"github.com/tal-tech/go-zero/core/syncx" "github.com/tal-tech/go-zero/core/syncx"
) )
@ -26,12 +27,12 @@ func init() {
} }
func TestCacheNode_DelCache(t *testing.T) { func TestCacheNode_DelCache(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())), r: rand.New(rand.NewSource(time.Now().UnixNano())),
lock: new(sync.Mutex), lock: new(sync.Mutex),
unstableExpiry: mathx.NewUnstable(expiryDeviation), unstableExpiry: mathx.NewUnstable(expiryDeviation),
@ -49,9 +50,9 @@ func TestCacheNode_DelCache(t *testing.T) {
} }
func TestCacheNode_InvalidCache(t *testing.T) { func TestCacheNode_InvalidCache(t *testing.T) {
s, clean, err := createMiniRedis() s, err := miniredis.Run()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer s.Close()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: redis.NewRedis(s.Addr(), redis.NodeType),
@ -70,12 +71,12 @@ func TestCacheNode_InvalidCache(t *testing.T) {
} }
func TestCacheNode_Take(t *testing.T) { func TestCacheNode_Take(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())), r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSharedCalls(), barrier: syncx.NewSharedCalls(),
lock: new(sync.Mutex), lock: new(sync.Mutex),
@ -91,18 +92,18 @@ func TestCacheNode_Take(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "value", str) assert.Equal(t, "value", str)
assert.Nil(t, cn.GetCache("any", &str)) assert.Nil(t, cn.GetCache("any", &str))
val, err := s.Get("any") val, err := store.Get("any")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, `"value"`, val) assert.Equal(t, `"value"`, val)
} }
func TestCacheNode_TakeNotFound(t *testing.T) { func TestCacheNode_TakeNotFound(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())), r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSharedCalls(), barrier: syncx.NewSharedCalls(),
lock: new(sync.Mutex), lock: new(sync.Mutex),
@ -116,18 +117,18 @@ func TestCacheNode_TakeNotFound(t *testing.T) {
}) })
assert.Equal(t, errTestNotFound, err) assert.Equal(t, errTestNotFound, err)
assert.Equal(t, errTestNotFound, cn.GetCache("any", &str)) assert.Equal(t, errTestNotFound, cn.GetCache("any", &str))
val, err := s.Get("any") val, err := store.Get("any")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, `*`, val) assert.Equal(t, `*`, val)
s.Set("any", "*") store.Set("any", "*")
err = cn.Take(&str, "any", func(v interface{}) error { err = cn.Take(&str, "any", func(v interface{}) error {
return nil return nil
}) })
assert.Equal(t, errTestNotFound, err) assert.Equal(t, errTestNotFound, err)
assert.Equal(t, errTestNotFound, cn.GetCache("any", &str)) assert.Equal(t, errTestNotFound, cn.GetCache("any", &str))
s.Del("any") store.Del("any")
var errDummy = errors.New("dummy") var errDummy = errors.New("dummy")
err = cn.Take(&str, "any", func(v interface{}) error { err = cn.Take(&str, "any", func(v interface{}) error {
return errDummy return errDummy
@ -136,12 +137,12 @@ func TestCacheNode_TakeNotFound(t *testing.T) {
} }
func TestCacheNode_TakeWithExpire(t *testing.T) { func TestCacheNode_TakeWithExpire(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())), r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSharedCalls(), barrier: syncx.NewSharedCalls(),
lock: new(sync.Mutex), lock: new(sync.Mutex),
@ -157,18 +158,18 @@ func TestCacheNode_TakeWithExpire(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "value", str) assert.Equal(t, "value", str)
assert.Nil(t, cn.GetCache("any", &str)) assert.Nil(t, cn.GetCache("any", &str))
val, err := s.Get("any") val, err := store.Get("any")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, `"value"`, val) assert.Equal(t, `"value"`, val)
} }
func TestCacheNode_String(t *testing.T) { func TestCacheNode_String(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())), r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSharedCalls(), barrier: syncx.NewSharedCalls(),
lock: new(sync.Mutex), lock: new(sync.Mutex),
@ -176,16 +177,16 @@ func TestCacheNode_String(t *testing.T) {
stat: NewCacheStat("any"), stat: NewCacheStat("any"),
errNotFound: errors.New("any"), errNotFound: errors.New("any"),
} }
assert.Equal(t, s.Addr(), cn.String()) assert.Equal(t, store.Addr, cn.String())
} }
func TestCacheValueWithBigInt(t *testing.T) { func TestCacheValueWithBigInt(t *testing.T) {
s, clean, err := createMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
cn := cacheNode{ cn := cacheNode{
rds: redis.NewRedis(s.Addr(), redis.NodeType), rds: store,
r: rand.New(rand.NewSource(time.Now().UnixNano())), r: rand.New(rand.NewSource(time.Now().UnixNano())),
barrier: syncx.NewSharedCalls(), barrier: syncx.NewSharedCalls(),
lock: new(sync.Mutex), lock: new(sync.Mutex),

@ -2,11 +2,8 @@ package cache
import ( import (
"testing" "testing"
"time"
"github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/lang"
) )
func TestFormatKeys(t *testing.T) { func TestFormatKeys(t *testing.T) {
@ -27,22 +24,3 @@ func TestTotalWeights(t *testing.T) {
}) })
assert.Equal(t, 1, val) assert.Equal(t, 1, val)
} }
func createMiniRedis() (r *miniredis.Miniredis, clean func(), err error) {
r, err = miniredis.Run()
if err != nil {
return nil, nil, err
}
return r, func() {
ch := make(chan lang.PlaceholderType)
go func() {
r.Close()
close(ch)
}()
select {
case <-ch:
case <-time.After(time.Second):
}
}, nil
}

@ -11,7 +11,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/alicebob/miniredis"
"github.com/globalsign/mgo" "github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson" "github.com/globalsign/mgo/bson"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -19,6 +18,7 @@ import (
"github.com/tal-tech/go-zero/core/stores/cache" "github.com/tal-tech/go-zero/core/stores/cache"
"github.com/tal-tech/go-zero/core/stores/mongo" "github.com/tal-tech/go-zero/core/stores/mongo"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redistest"
) )
func init() { func init() {
@ -27,12 +27,10 @@ func init() {
func TestStat(t *testing.T) { func TestStat(t *testing.T) {
resetStats() resetStats()
s, err := miniredis.Run() r, clean, err := redistest.CreateRedis()
if err != nil { assert.Nil(t, err)
t.Error(err) defer clean()
}
r := redis.NewRedis(s.Addr(), redis.NodeType)
cach := cache.NewCacheNode(r, sharedCalls, stats, mgo.ErrNotFound) cach := cache.NewCacheNode(r, sharedCalls, stats, mgo.ErrNotFound)
c := newCollection(dummyConn{}, cach) c := newCollection(dummyConn{}, cach)
@ -73,12 +71,10 @@ func TestStatCacheFails(t *testing.T) {
func TestStatDbFails(t *testing.T) { func TestStatDbFails(t *testing.T) {
resetStats() resetStats()
s, err := miniredis.Run() r, clean, err := redistest.CreateRedis()
if err != nil { assert.Nil(t, err)
t.Error(err) defer clean()
}
r := redis.NewRedis(s.Addr(), redis.NodeType)
cach := cache.NewCacheNode(r, sharedCalls, stats, mgo.ErrNotFound) cach := cache.NewCacheNode(r, sharedCalls, stats, mgo.ErrNotFound)
c := newCollection(dummyConn{}, cach) c := newCollection(dummyConn{}, cach)
@ -97,12 +93,10 @@ func TestStatDbFails(t *testing.T) {
func TestStatFromMemory(t *testing.T) { func TestStatFromMemory(t *testing.T) {
resetStats() resetStats()
s, err := miniredis.Run() r, clean, err := redistest.CreateRedis()
if err != nil { assert.Nil(t, err)
t.Error(err) defer clean()
}
r := redis.NewRedis(s.Addr(), redis.NodeType)
cach := cache.NewCacheNode(r, sharedCalls, stats, mgo.ErrNotFound) cach := cache.NewCacheNode(r, sharedCalls, stats, mgo.ErrNotFound)
c := newCollection(dummyConn{}, cach) c := newCollection(dummyConn{}, cach)

@ -0,0 +1,28 @@
package redistest
import (
"time"
"github.com/alicebob/miniredis"
"github.com/tal-tech/go-zero/core/lang"
"github.com/tal-tech/go-zero/core/stores/redis"
)
func CreateRedis() (r *redis.Redis, clean func(), err error) {
mr, err := miniredis.Run()
if err != nil {
return nil, nil, err
}
return redis.NewRedis(mr.Addr(), redis.NodeType), func() {
ch := make(chan lang.PlaceholderType)
go func() {
mr.Close()
close(ch)
}()
select {
case <-ch:
case <-time.After(time.Second):
}
}, nil
}

@ -16,11 +16,11 @@ import (
"github.com/alicebob/miniredis" "github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/lang"
"github.com/tal-tech/go-zero/core/logx" "github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/stat" "github.com/tal-tech/go-zero/core/stat"
"github.com/tal-tech/go-zero/core/stores/cache" "github.com/tal-tech/go-zero/core/stores/cache"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redis"
"github.com/tal-tech/go-zero/core/stores/redistest"
"github.com/tal-tech/go-zero/core/stores/sqlx" "github.com/tal-tech/go-zero/core/stores/sqlx"
) )
@ -31,16 +31,15 @@ func init() {
func TestCachedConn_GetCache(t *testing.T) { func TestCachedConn_GetCache(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10))
var value string var value string
err = c.GetCache("any", &value) err = c.GetCache("any", &value)
assert.Equal(t, ErrNotFound, err) assert.Equal(t, ErrNotFound, err)
s.Set("any", `"value"`) r.Set("any", `"value"`)
err = c.GetCache("any", &value) err = c.GetCache("any", &value)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "value", value) assert.Equal(t, "value", value)
@ -48,11 +47,10 @@ func TestCachedConn_GetCache(t *testing.T) {
func TestStat(t *testing.T) { func TestStat(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10))
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
@ -72,15 +70,14 @@ func TestStat(t *testing.T) {
func TestCachedConn_QueryRowIndex_NoCache(t *testing.T) { func TestCachedConn_QueryRowIndex_NoCache(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewConn(dummySqlConn{}, cache.CacheConf{ c := NewConn(dummySqlConn{}, cache.CacheConf{
{ {
RedisConf: redis.RedisConf{ RedisConf: redis.RedisConf{
Host: s.Addr(), Host: r.Addr,
Type: redis.NodeType, Type: redis.NodeType,
}, },
Weight: 100, Weight: 100,
@ -122,11 +119,10 @@ func TestCachedConn_QueryRowIndex_NoCache(t *testing.T) {
func TestCachedConn_QueryRowIndex_HasCache(t *testing.T) { func TestCachedConn_QueryRowIndex_HasCache(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10), c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10),
cache.WithNotFoundExpiry(time.Second)) cache.WithNotFoundExpiry(time.Second))
@ -210,16 +206,13 @@ func TestCachedConn_QueryRowIndex_HasCache_IntPrimary(t *testing.T) {
}, },
} }
s, clean, err := createMiniRedis()
assert.Nil(t, err)
defer clean()
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
resetStats() resetStats()
s.FlushAll() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err)
defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10), c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10),
cache.WithNotFoundExpiry(time.Second)) cache.WithNotFoundExpiry(time.Second))
@ -256,11 +249,10 @@ func TestCachedConn_QueryRowIndex_HasWrongCache(t *testing.T) {
for k, v := range caches { for k, v := range caches {
t.Run(k+"/"+v, func(t *testing.T) { t.Run(k+"/"+v, func(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10), c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10),
cache.WithNotFoundExpiry(time.Second)) cache.WithNotFoundExpiry(time.Second))
@ -312,11 +304,10 @@ func TestStatCacheFails(t *testing.T) {
func TestStatDbFails(t *testing.T) { func TestStatDbFails(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10))
for i := 0; i < 20; i++ { for i := 0; i < 20; i++ {
@ -334,11 +325,10 @@ func TestStatDbFails(t *testing.T) {
func TestStatFromMemory(t *testing.T) { func TestStatFromMemory(t *testing.T) {
resetStats() resetStats()
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(dummySqlConn{}, r, cache.WithExpiry(time.Second*10))
var all sync.WaitGroup var all sync.WaitGroup
@ -393,7 +383,7 @@ func TestStatFromMemory(t *testing.T) {
} }
func TestCachedConnQueryRow(t *testing.T) { func TestCachedConnQueryRow(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
@ -404,7 +394,6 @@ func TestCachedConnQueryRow(t *testing.T) {
var conn trackedConn var conn trackedConn
var user string var user string
var ran bool var ran bool
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30)) c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30))
err = c.QueryRow(&user, key, func(conn sqlx.SqlConn, v interface{}) error { err = c.QueryRow(&user, key, func(conn sqlx.SqlConn, v interface{}) error {
ran = true ran = true
@ -412,7 +401,7 @@ func TestCachedConnQueryRow(t *testing.T) {
return nil return nil
}) })
assert.Nil(t, err) assert.Nil(t, err)
actualValue, err := s.Get(key) actualValue, err := r.Get(key)
assert.Nil(t, err) assert.Nil(t, err)
var actual string var actual string
assert.Nil(t, json.Unmarshal([]byte(actualValue), &actual)) assert.Nil(t, json.Unmarshal([]byte(actualValue), &actual))
@ -422,7 +411,7 @@ func TestCachedConnQueryRow(t *testing.T) {
} }
func TestCachedConnQueryRowFromCache(t *testing.T) { func TestCachedConnQueryRowFromCache(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
@ -433,7 +422,6 @@ func TestCachedConnQueryRowFromCache(t *testing.T) {
var conn trackedConn var conn trackedConn
var user string var user string
var ran bool var ran bool
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30)) c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30))
assert.Nil(t, c.SetCache(key, value)) assert.Nil(t, c.SetCache(key, value))
err = c.QueryRow(&user, key, func(conn sqlx.SqlConn, v interface{}) error { err = c.QueryRow(&user, key, func(conn sqlx.SqlConn, v interface{}) error {
@ -442,7 +430,7 @@ func TestCachedConnQueryRowFromCache(t *testing.T) {
return nil return nil
}) })
assert.Nil(t, err) assert.Nil(t, err)
actualValue, err := s.Get(key) actualValue, err := r.Get(key)
assert.Nil(t, err) assert.Nil(t, err)
var actual string var actual string
assert.Nil(t, json.Unmarshal([]byte(actualValue), &actual)) assert.Nil(t, json.Unmarshal([]byte(actualValue), &actual))
@ -452,7 +440,7 @@ func TestCachedConnQueryRowFromCache(t *testing.T) {
} }
func TestQueryRowNotFound(t *testing.T) { func TestQueryRowNotFound(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
@ -460,7 +448,6 @@ func TestQueryRowNotFound(t *testing.T) {
var conn trackedConn var conn trackedConn
var user string var user string
var ran int var ran int
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30)) c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30))
for i := 0; i < 20; i++ { for i := 0; i < 20; i++ {
err = c.QueryRow(&user, key, func(conn sqlx.SqlConn, v interface{}) error { err = c.QueryRow(&user, key, func(conn sqlx.SqlConn, v interface{}) error {
@ -473,12 +460,11 @@ func TestQueryRowNotFound(t *testing.T) {
} }
func TestCachedConnExec(t *testing.T) { func TestCachedConnExec(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
var conn trackedConn var conn trackedConn
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*10))
_, err = c.ExecNoCache("delete from user_table where id='kevin'") _, err = c.ExecNoCache("delete from user_table where id='kevin'")
assert.Nil(t, err) assert.Nil(t, err)
@ -486,24 +472,23 @@ func TestCachedConnExec(t *testing.T) {
} }
func TestCachedConnExecDropCache(t *testing.T) { func TestCachedConnExecDropCache(t *testing.T) {
s, clean, err := createMiniRedis() r, err := miniredis.Run()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer r.Close()
const ( const (
key = "user" key = "user"
value = "any" value = "any"
) )
var conn trackedConn var conn trackedConn
r := redis.NewRedis(s.Addr(), redis.NodeType) c := NewNodeConn(&conn, redis.NewRedis(r.Addr(), redis.NodeType), cache.WithExpiry(time.Second*30))
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*30))
assert.Nil(t, c.SetCache(key, value)) assert.Nil(t, c.SetCache(key, value))
_, err = c.Exec(func(conn sqlx.SqlConn) (result sql.Result, e error) { _, err = c.Exec(func(conn sqlx.SqlConn) (result sql.Result, e error) {
return conn.Exec("delete from user_table where id='kevin'") return conn.Exec("delete from user_table where id='kevin'")
}, key) }, key)
assert.Nil(t, err) assert.Nil(t, err)
assert.True(t, conn.execValue) assert.True(t, conn.execValue)
_, err = s.Get(key) _, err = r.Get(key)
assert.Exactly(t, miniredis.ErrKeyNotFound, err) assert.Exactly(t, miniredis.ErrKeyNotFound, err)
_, err = c.Exec(func(conn sqlx.SqlConn) (result sql.Result, e error) { _, err = c.Exec(func(conn sqlx.SqlConn) (result sql.Result, e error) {
return nil, errors.New("foo") return nil, errors.New("foo")
@ -524,12 +509,11 @@ func TestCachedConnExecDropCacheFailed(t *testing.T) {
} }
func TestCachedConnQueryRows(t *testing.T) { func TestCachedConnQueryRows(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
var conn trackedConn var conn trackedConn
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*10))
var users []string var users []string
err = c.QueryRowsNoCache(&users, "select user from user_table where id='kevin'") err = c.QueryRowsNoCache(&users, "select user from user_table where id='kevin'")
@ -538,12 +522,11 @@ func TestCachedConnQueryRows(t *testing.T) {
} }
func TestCachedConnTransact(t *testing.T) { func TestCachedConnTransact(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
var conn trackedConn var conn trackedConn
r := redis.NewRedis(s.Addr(), redis.NodeType)
c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*10)) c := NewNodeConn(&conn, r, cache.WithExpiry(time.Second*10))
err = c.Transact(func(session sqlx.Session) error { err = c.Transact(func(session sqlx.Session) error {
return nil return nil
@ -553,7 +536,7 @@ func TestCachedConnTransact(t *testing.T) {
} }
func TestQueryRowNoCache(t *testing.T) { func TestQueryRowNoCache(t *testing.T) {
s, clean, err := createMiniRedis() r, clean, err := redistest.CreateRedis()
assert.Nil(t, err) assert.Nil(t, err)
defer clean() defer clean()
@ -563,7 +546,6 @@ func TestQueryRowNoCache(t *testing.T) {
) )
var user string var user string
var ran bool var ran bool
r := redis.NewRedis(s.Addr(), redis.NodeType)
conn := dummySqlConn{queryRow: func(v interface{}, q string, args ...interface{}) error { conn := dummySqlConn{queryRow: func(v interface{}, q string, args ...interface{}) error {
user = value user = value
ran = true ran = true
@ -639,22 +621,3 @@ func (c *trackedConn) Transact(fn func(session sqlx.Session) error) error {
c.transactValue = true c.transactValue = true
return c.dummySqlConn.Transact(fn) return c.dummySqlConn.Transact(fn)
} }
func createMiniRedis() (r *miniredis.Miniredis, clean func(), err error) {
r, err = miniredis.Run()
if err != nil {
return nil, nil, err
}
return r, func() {
ch := make(chan lang.PlaceholderType)
go func() {
r.Close()
close(ch)
}()
select {
case <-ch:
case <-time.After(time.Second):
}
}, nil
}

@ -16,6 +16,8 @@ go-zero 是一个集成了各种工程实践的 web 和 rpc 框架。通过弹
go-zero 包含极简的 API 定义和生成工具 goctl可以根据定义的 api 文件一键生成 Go, iOS, Android, Kotlin, Dart, TypeScript, JavaScript 代码,并可直接运行。 go-zero 包含极简的 API 定义和生成工具 goctl可以根据定义的 api 文件一键生成 Go, iOS, Android, Kotlin, Dart, TypeScript, JavaScript 代码,并可直接运行。
看着觉得不错的,烦请 **Star**
使用 go-zero 的好处: 使用 go-zero 的好处:
* 轻松获得支撑千万日活服务的稳定性 * 轻松获得支撑千万日活服务的稳定性

@ -4,9 +4,8 @@ import (
"context" "context"
"testing" "testing"
"github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redistest"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
) )
@ -44,13 +43,12 @@ func TestAuthenticator(t *testing.T) {
}, },
} }
r := miniredis.NewMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, r.Start()) assert.Nil(t, err)
defer r.Close() defer clean()
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
store := redis.NewRedis(r.Addr(), redis.NodeType)
if len(test.app) > 0 { if len(test.app) > 0 {
assert.Nil(t, store.Hset("apps", test.app, test.token)) assert.Nil(t, store.Hset("apps", test.app, test.token))
defer store.Hdel("apps", test.app) defer store.Hdel("apps", test.app)

@ -4,9 +4,8 @@ import (
"context" "context"
"testing" "testing"
"github.com/alicebob/miniredis"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/stores/redis" "github.com/tal-tech/go-zero/core/stores/redistest"
"github.com/tal-tech/go-zero/zrpc/internal/auth" "github.com/tal-tech/go-zero/zrpc/internal/auth"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
@ -46,13 +45,12 @@ func TestStreamAuthorizeInterceptor(t *testing.T) {
}, },
} }
r := miniredis.NewMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, r.Start()) assert.Nil(t, err)
defer r.Close() defer clean()
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
store := redis.NewRedis(r.Addr(), redis.NodeType)
if len(test.app) > 0 { if len(test.app) > 0 {
assert.Nil(t, store.Hset("apps", test.app, test.token)) assert.Nil(t, store.Hset("apps", test.app, test.token))
defer store.Hdel("apps", test.app) defer store.Hdel("apps", test.app)
@ -113,13 +111,12 @@ func TestUnaryAuthorizeInterceptor(t *testing.T) {
}, },
} }
r := miniredis.NewMiniRedis() store, clean, err := redistest.CreateRedis()
assert.Nil(t, r.Start()) assert.Nil(t, err)
defer r.Close() defer clean()
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
store := redis.NewRedis(r.Addr(), redis.NodeType)
if len(test.app) > 0 { if len(test.app) > 0 {
assert.Nil(t, store.Hset("apps", test.app, test.token)) assert.Nil(t, store.Hset("apps", test.app, test.token))
defer store.Hdel("apps", test.app) defer store.Hdel("apps", test.app)

Loading…
Cancel
Save