Skip to content

test(coderd/database/dbtestutil): allow access to *sql.DB #10238

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

Merged
merged 3 commits into from
Oct 12, 2023
Merged
Changes from all commits
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
25 changes: 25 additions & 0 deletions coderd/database/dbtestutil/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func WillUsePostgres() bool {
type options struct {
fixedTimezone string
dumpOnFailure bool
returnSQLDB func(*sql.DB)
}

type Option func(*options)
Expand All @@ -49,6 +50,27 @@ func WithDumpOnFailure() Option {
}
}

func withReturnSQLDB(f func(*sql.DB)) Option {
return func(o *options) {
o.returnSQLDB = f
}
}

func NewDBWithSQLDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub, *sql.DB) {
t.Helper()

if !WillUsePostgres() {
t.Fatal("cannot use NewDBWithSQLDB without PostgreSQL, consider adding `if !dbtestutil.WillUsePostgres() { t.Skip() }` to this test")
}

var sqlDB *sql.DB
opts = append(opts, withReturnSQLDB(func(db *sql.DB) {
sqlDB = db
}))
Comment on lines +67 to +69
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotta love functional options <3

db, ps := NewDB(t, opts...)
return db, ps, sqlDB
}

func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) {
t.Helper()

Expand Down Expand Up @@ -88,6 +110,9 @@ func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) {
t.Cleanup(func() {
_ = sqlDB.Close()
})
if o.returnSQLDB != nil {
o.returnSQLDB(sqlDB)
}
Comment on lines +113 to +115
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if dbtestutil.WillUsePostgres is false? I could see this being a potential sharp edge. It would probably be a good idea to fail the test if this is defined and we're using the fakeDB.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch 👍🏻, I'll return an error.

if o.dumpOnFailure {
t.Cleanup(func() { DumpOnFailure(t, connectionURL) })
}
Expand Down