From 64995854a3a71e21181a8f7a023f7e9b55bc33f6 Mon Sep 17 00:00:00 2001 From: Timothy Messier Date: Fri, 5 Jan 2024 13:34:51 -0500 Subject: [PATCH] feat(dbtest): Allow host to be configurable (#2538) Normally the tests are run on a host machine with a docker container for the database. The docker container should be accessible via 127.0.0.1. However there might be cases where the test execution is run in a docker container, or the postgres server is configured to use a different docker network, in which case the container would be accessible via some other dns name or ip. In these cases, users can now set the TEST_DB_HOST environment variable so the tests can connect to the postgres server. --- testing/dbtest/template.go | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/testing/dbtest/template.go b/testing/dbtest/template.go index cc6842a81..3e4beaaa9 100644 --- a/testing/dbtest/template.go +++ b/testing/dbtest/template.go @@ -19,10 +19,10 @@ import ( _ "github.com/jackc/pgx/v5/stdlib" ) -var testDBPort = "5432" - -// StartUsingTemplate creates a new test database from a postgres template database. -var StartUsingTemplate func(dialect string, opt ...Option) (func() error, string, string, error) = startUsingTemplate +var ( + testDBPort = "5432" + testDBHost = "127.0.0.1" +) func init() { rand.Seed(time.Now().UnixNano()) @@ -31,6 +31,10 @@ func init() { if p != "" { testDBPort = p } + h := os.Getenv("TEST_DB_HOST") + if h != "" { + testDBHost = h + } } // Dialects @@ -110,7 +114,8 @@ func randStr(n int) string { return string(b) } -func startUsingTemplate(dialect string, opt ...Option) (cleanup func() error, retURL, dbname string, err error) { +// StartUsingTemplate creates a new test database from a postgres template database. +func StartUsingTemplate(dialect string, opt ...Option) (cleanup func() error, retURL, dbname string, err error) { if _, ok := supportedDialects[dialect]; !ok { return func() error { return nil }, "", "", fmt.Errorf("unsupported dialect: %s", dialect) } @@ -118,7 +123,7 @@ func startUsingTemplate(dialect string, opt ...Option) (cleanup func() error, re if dialect == "postgres" { dialect = "pgx" } - db, err := common.SqlOpen(dialect, fmt.Sprintf("postgres://boundary:boundary@127.0.0.1:%s/boundary?sslmode=disable", testDBPort)) + db, err := common.SqlOpen(dialect, fmt.Sprintf("postgres://boundary:boundary@%s:%s/boundary?sslmode=disable", testDBHost, testDBPort)) if err != nil { return func() error { return nil }, "", "", fmt.Errorf("could not connect to source database: %w", err) }