2022-03-31 13:21:18 +00:00
|
|
|
package shopfront_test
|
|
|
|
|
|
|
|
import (
|
2023-03-06 09:57:51 +00:00
|
|
|
"context"
|
2022-03-31 13:21:18 +00:00
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"time"
|
|
|
|
|
2023-03-06 09:57:51 +00:00
|
|
|
"github.com/go-redis/redis/v8"
|
2022-03-31 13:21:18 +00:00
|
|
|
"github.com/stretchr/testify/require"
|
2022-04-17 15:28:33 +00:00
|
|
|
|
2023-10-03 17:25:41 +00:00
|
|
|
"gitlab.com/manytask/itmo-go/public/tools/testtool"
|
2022-03-31 13:21:18 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type testingTB interface {
|
|
|
|
Logf(format string, args ...interface{})
|
|
|
|
Fatalf(format string, args ...interface{})
|
|
|
|
Errorf(format string, args ...interface{})
|
|
|
|
FailNow()
|
|
|
|
Cleanup(func())
|
|
|
|
}
|
|
|
|
|
|
|
|
func StartRedis(tb testingTB) string {
|
|
|
|
if redis, ok := os.LookupEnv("REDIS"); ok {
|
|
|
|
tb.Logf("using external redis server; REDIS=%s", redis)
|
|
|
|
return redis
|
|
|
|
}
|
|
|
|
|
|
|
|
port, err := testtool.GetFreePort()
|
|
|
|
require.NoError(tb, err)
|
|
|
|
|
|
|
|
_, err = exec.LookPath("redis-server")
|
|
|
|
if err != nil {
|
|
|
|
tb.Fatalf("redis-server binary is not found; is redis installed?")
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd := exec.Command("redis-server", "--port", port, "--save", "", "--appendonly", "no")
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
|
|
|
|
require.NoError(tb, cmd.Start())
|
2023-03-06 09:57:51 +00:00
|
|
|
tb.Cleanup(func() {
|
|
|
|
_ = cmd.Process.Kill()
|
|
|
|
})
|
2022-03-31 13:21:18 +00:00
|
|
|
|
|
|
|
finished := make(chan error, 1)
|
|
|
|
go func() {
|
|
|
|
finished <- cmd.Wait()
|
|
|
|
}()
|
|
|
|
|
2023-03-06 09:57:51 +00:00
|
|
|
redisAddress := "localhost:" + port
|
|
|
|
startTimeout := time.After(time.Second * 5)
|
2022-03-31 13:21:18 +00:00
|
|
|
|
2023-03-06 09:57:51 +00:00
|
|
|
loop:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case err := <-finished:
|
|
|
|
tb.Fatalf("redis server terminated: %v", err)
|
2022-03-31 13:21:18 +00:00
|
|
|
|
2023-03-06 09:57:51 +00:00
|
|
|
case <-startTimeout:
|
|
|
|
tb.Fatalf("redis not started after timeout")
|
|
|
|
|
|
|
|
default:
|
|
|
|
time.Sleep(time.Millisecond * 50)
|
|
|
|
|
|
|
|
rdb := redis.NewClient(&redis.Options{Addr: redisAddress})
|
|
|
|
status := rdb.Ping(context.Background())
|
|
|
|
_ = rdb.Close()
|
|
|
|
|
|
|
|
if status.Err() == nil {
|
|
|
|
break loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-31 13:21:18 +00:00
|
|
|
|
2023-03-06 09:57:51 +00:00
|
|
|
return redisAddress
|
2022-03-31 13:21:18 +00:00
|
|
|
}
|