Files

57 lines
1.7 KiB
Go

// Package redisserver 仅为测试启动监听临时 Unix socket 的独立 Redis。
package redisserver
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/redis/go-redis/v9"
)
// New 创建隔离测试客户端,不连接部署配置中的任何实例。
// 入参:t 为测试生命周期,protocol 为 RESP 协议版本。
// 返回:可清空和关闭的测试客户端;环境无 redis-server 时跳过。
func New(t *testing.T, protocol int) *redis.Client {
var (
server, err = exec.LookPath("redis-server")
directory string
command *exec.Cmd
client *redis.Client
deadline time.Time
)
t.Helper()
if err != nil {
t.Skip("redis-server is required for isolated Redis integration tests")
}
if directory, err = os.MkdirTemp("", "gf-"); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(directory) })
command = exec.Command(server, "--port", "0", "--unixsocket", filepath.Join(directory, "redis.sock"), "--save", "", "--appendonly", "no")
command.Stderr = os.Stderr
if err = command.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = command.Process.Kill(); _ = command.Wait() })
client = redis.NewClient(&redis.Options{
Network: "unix",
Addr: filepath.Join(directory, "redis.sock"),
Protocol: protocol,
MaxRetries: -1,
ContextTimeoutEnabled: true,
})
t.Cleanup(func() { _ = client.Close() })
deadline = time.Now().Add(5 * time.Second)
for client.Ping(context.Background()).Err() != nil {
if time.Now().After(deadline) {
t.Fatal("isolated Redis did not start")
}
time.Sleep(10 * time.Millisecond)
}
return client
}