mirror of
https://github.com/coder/coder.git
synced 2025-07-06 15:41:45 +00:00
* chore: add /v2 to import module path go mod requires semantic versioning with versions greater than 1.x This was a mechanical update by running: ``` go install github.com/marwan-at-work/mod/cmd/mod@latest mod upgrade ``` Migrate generated files to import /v2 * Fix gen
54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package dbtestutil
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"os"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
"github.com/coder/coder/v2/coderd/database/dbfake"
|
|
"github.com/coder/coder/v2/coderd/database/postgres"
|
|
"github.com/coder/coder/v2/coderd/database/pubsub"
|
|
)
|
|
|
|
// WillUsePostgres returns true if a call to NewDB() will return a real, postgres-backed Store and Pubsub.
|
|
func WillUsePostgres() bool {
|
|
return os.Getenv("DB") != ""
|
|
}
|
|
|
|
func NewDB(t testing.TB) (database.Store, pubsub.Pubsub) {
|
|
t.Helper()
|
|
|
|
db := dbfake.New()
|
|
ps := pubsub.NewInMemory()
|
|
if WillUsePostgres() {
|
|
connectionURL := os.Getenv("CODER_PG_CONNECTION_URL")
|
|
if connectionURL == "" {
|
|
var (
|
|
err error
|
|
closePg func()
|
|
)
|
|
connectionURL, closePg, err = postgres.Open()
|
|
require.NoError(t, err)
|
|
t.Cleanup(closePg)
|
|
}
|
|
sqlDB, err := sql.Open("postgres", connectionURL)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() {
|
|
_ = sqlDB.Close()
|
|
})
|
|
db = database.New(sqlDB)
|
|
|
|
ps, err = pubsub.New(context.Background(), sqlDB, connectionURL)
|
|
require.NoError(t, err)
|
|
t.Cleanup(func() {
|
|
_ = ps.Close()
|
|
})
|
|
}
|
|
|
|
return db, ps
|
|
}
|