package db import ( "errors" "fmt" "os" "strings" "testing" ) func TestMain(m *testing.M) { if err := testConnectAndInit(); nil != err { fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) return } os.Exit(m.Run()) } func needsTestDB() (string, error) { connStr := os.Getenv("TEST_DATABASE_URL") if "" == connStr { return "", errors.New(`no connection string defined You must set TEST_DATABASE_URL to run db tests. You may find this helpful: psql 'postgres://postgres:postgres@localhost:5432/postgres' DROP DATABASE IF EXISTS postgres_test; CREATE DATABASE postgres_test; \q Then your test database URL will be export TEST_DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres_test`) } return connStr, nil } func testConnectAndInit() error { connStr, err := needsTestDB() if nil != err { return err } if strings.Contains(connStr, "@localhost/") || strings.Contains(connStr, "@localhost:") { connStr += "?sslmode=disable" } else { connStr += "?sslmode=required" } if err := Init(connStr); nil != err { return fmt.Errorf("db connection error: %w", err) } return nil } func TestDropAll(t *testing.T) { connStr := os.Getenv("TEST_DATABASE_URL") if err := DropAllTables(PleaseDoubleCheckTheDatabaseURLDontDropProd(connStr)); nil != err { t.Fatal(err) } }