2022-03-26 12:52:25 +00:00
|
|
|
package pgfixture
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2022-03-26 13:12:29 +00:00
|
|
|
"io/ioutil"
|
2022-03-26 12:52:25 +00:00
|
|
|
"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-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 := ioutil.ReadDir(ubuntuPostgres); err == nil {
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
|
|
|
pgrun := t.TempDir()
|
|
|
|
|
2022-03-26 13:12:29 +00:00
|
|
|
cmd = exec.Command(lookPath(t, "postgres"), "-D", pgdata, "-k", pgrun, "-F")
|
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()
|
|
|
|
})
|
|
|
|
|
|
|
|
return fmt.Sprintf("host=%s database=postgres", pgrun)
|
|
|
|
}
|