105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package redis_test
|
|
|
|
import (
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
|
|
"apigo.cc/go/config"
|
|
"apigo.cc/go/redis"
|
|
)
|
|
|
|
type userInfo struct {
|
|
Id int
|
|
Name string
|
|
Phone string
|
|
Time time.Time
|
|
}
|
|
|
|
func TestBase(t *testing.T) {
|
|
os.Setenv("REDIS_TEST", "redis://:@localhost:6379/2?timeout=10ms&logSlow=10us")
|
|
_ = config.Load("redis", nil)
|
|
|
|
rd := redis.GetRedis("test", nil)
|
|
if rd.Error != nil {
|
|
t.Fatal("GetRedis error", rd.Error)
|
|
}
|
|
rd.DEL("redisName", "redisUser", "redisIds")
|
|
|
|
r := rd.GET("redisNotExists")
|
|
if r.Error != nil && r.String() != "" || r.Int() != 0 {
|
|
t.Fatal("GET NotExists", r, r.String(), r.Int())
|
|
}
|
|
|
|
exists := rd.EXISTS("redisName")
|
|
if exists {
|
|
t.Fatal("EXISTS should be false")
|
|
}
|
|
|
|
rd.SET("redisName", "12345")
|
|
|
|
r = rd.GETSET("redisName", 12345)
|
|
if r.String() != "12345" {
|
|
t.Fatal("GETSET String mismatch", r.String())
|
|
}
|
|
if r.Int() != 12345 {
|
|
t.Fatal("Int conversion mismatch", r.Int())
|
|
}
|
|
|
|
exists = rd.EXISTS("redisName")
|
|
if !exists {
|
|
t.Fatal("EXISTS should be true")
|
|
}
|
|
|
|
// Expire test
|
|
rd.SET("redisName", "12")
|
|
rd.EXPIRE("redisName", 1)
|
|
time.Sleep(2 * time.Second)
|
|
r = rd.GET("redisName")
|
|
if r.Int() > 0 {
|
|
t.Fatal("Expired key still exists", r.Int())
|
|
}
|
|
|
|
// Struct test
|
|
info := userInfo{
|
|
Name: "aaa",
|
|
Id: 123,
|
|
Time: time.Now().Truncate(time.Second), // Redis JSON might lose precision
|
|
}
|
|
rd.SET("redisUser", info)
|
|
r = rd.GET("redisUser")
|
|
var ru userInfo
|
|
_ = r.To(&ru)
|
|
if ru.Name != info.Name || ru.Id != info.Id || !ru.Time.Equal(info.Time) {
|
|
t.Fatalf("Struct mismatch: expected %+v, got %+v", info, ru)
|
|
}
|
|
|
|
// MSET/MGET test
|
|
rd.MSET("redisName", "Sam Lee", "redisIds", []int{1, 2, 3})
|
|
results := rd.MGET("redisName", "redisIds")
|
|
if len(results) != 2 || results[0].String() != "Sam Lee" {
|
|
t.Fatal("MGET Results mismatch")
|
|
}
|
|
ria := results[1].Ints()
|
|
if len(ria) != 3 || ria[0] != 1 || ria[1] != 2 || ria[2] != 3 {
|
|
t.Fatal("MGET Ints mismatch", ria)
|
|
}
|
|
|
|
num := rd.DEL("redisName", "redisUser", "redisIds")
|
|
if num != 3 {
|
|
t.Fatal("DEL count mismatch", num)
|
|
}
|
|
}
|
|
|
|
func TestGenerics(t *testing.T) {
|
|
rd := redis.GetRedis("test", nil)
|
|
rd.SET("gen_test", userInfo{Name: "Generics", Id: 888})
|
|
defer rd.DEL("gen_test")
|
|
|
|
r := rd.GET("gen_test")
|
|
user := redis.To[userInfo](r)
|
|
if user.Name != "Generics" || user.Id != 888 {
|
|
t.Fatal("Generics To[T] mismatch", user)
|
|
}
|
|
}
|