shad-go/pgfixture/pg.go

86 lines
1.6 KiB
Go
Raw Permalink Normal View History

2022-03-26 12:52:25 +00:00
package pgfixture
import (
"fmt"
"os"
"os/exec"
2022-03-26 13:12:29 +00:00
"path/filepath"
2022-03-26 12:52:25 +00:00
"testing"
"time"
2022-03-31 13:30:47 +00:00
"github.com/stretchr/testify/require"
2022-04-17 15:28:33 +00:00
"gitlab.com/slon/shad-go/tools/testtool"
2022-03-26 12:52:25 +00:00
)
2022-03-26 13:12:29 +00:00
func lookPath(t *testing.T, name string) string {
t.Helper()
path, err := exec.LookPath(name)
if err == nil {
return path
}
const ubuntuPostgres = "/usr/lib/postgresql"
if dirs, err := os.ReadDir(ubuntuPostgres); err == nil {
2022-03-26 13:12:29 +00:00
for _, d := range dirs {
path := filepath.Join(ubuntuPostgres, d.Name(), "bin", name)
if _, err := os.Stat(path); err == nil {
return path
}
}
}
t.Fatalf("%s binary not found; is postgres installed?", name)
return ""
}
2022-03-26 12:52:25 +00:00
func Start(t *testing.T) string {
pgconn, ok := os.LookupEnv("PGCONN")
if ok {
t.Logf("using external database: PGCONN=%s", pgconn)
return pgconn
}
pgdata := t.TempDir()
2022-03-26 13:12:29 +00:00
cmd := exec.Command(lookPath(t, "initdb"), "-N", "-D", pgdata)
2022-03-26 12:52:25 +00:00
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
2022-03-26 13:12:29 +00:00
if err := cmd.Run(); err != nil {
2022-03-26 12:52:25 +00:00
t.Fatalf("initdb failed: %v", err)
}
2022-03-31 13:30:47 +00:00
port, err := testtool.GetFreePort()
require.NoError(t, err)
2022-03-26 12:52:25 +00:00
pgrun := t.TempDir()
2022-03-31 13:30:47 +00:00
cmd = exec.Command(lookPath(t, "postgres"), "-D", pgdata, "-k", pgrun, "-F", "-p", port)
2022-03-26 12:52:25 +00:00
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
2022-03-26 13:12:29 +00:00
if err := cmd.Start(); err != nil {
2022-03-26 12:52:25 +00:00
t.Fatalf("postgres failed: %v", err)
}
finished := make(chan error, 1)
go func() {
finished <- cmd.Wait()
}()
select {
2022-03-26 13:12:29 +00:00
case err := <-finished:
2022-03-26 12:52:25 +00:00
t.Fatalf("postgres server terminated: %v", err)
case <-time.After(time.Second / 2):
}
t.Cleanup(func() {
_ = cmd.Process.Kill()
})
2022-03-31 13:30:47 +00:00
return fmt.Sprintf("host=localhost port=%s database=postgres", port)
2022-03-26 12:52:25 +00:00
}