Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tests: enable configuring an external database for tests #1127

Merged
merged 2 commits into from
Oct 6, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions internal/db/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,39 @@ import (
_ "github.com/lib/pq"
)

const (
// UseExternalDBEnvVar is the environment variable that, when set, will
// enable using an external postgres database instead of the in-process one.
// Useful for debugging.
UseExternalDBEnvVar = "MEDIATOR_TEST_EXTERNAL_DB"
)

var testQueries *Queries
var testDB *sql.DB

func TestMain(m *testing.M) {
os.Exit(runTestWithPostgres(m))
var runDBTests = runTestWithInProcessPostgres
if useExternalDB() {
log.Println("Using external database for tests")
runDBTests = runTestWithExternalPostgres
}
os.Exit(runDBTests(m))
}

func runTestWithExternalPostgres(m *testing.M) int {
connStr := "user=postgres dbname=mediator password=postgres host=localhost sslmode=disable"

testDB, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal("cannot connect to db test instance:", err)
}

testQueries = New(testDB)

return m.Run()
}

func runTestWithPostgres(m *testing.M) int {
func runTestWithInProcessPostgres(m *testing.M) int {
tmpName, err := os.MkdirTemp("", "mediator-db-test")
if err != nil {
log.Println("cannot create tmpdir:", err)
Expand Down Expand Up @@ -97,3 +122,8 @@ func runTestWithPostgres(m *testing.M) int {
// Run tests
return m.Run()
}

func useExternalDB() bool {
_, ok := os.LookupEnv(UseExternalDBEnvVar)
return ok
}