chore: add postgres template caching for tests (#15336)

This PR is the first in a series aimed at closing
[#15109](https://github.com/coder/coder/issues/15109).

### Changes

- **Template Database Creation:**  
`dbtestutil.Open` now has the ability to create a template database if
none is provided via `DB_FROM`. The template database’s name is derived
from a hash of the migration files, ensuring that it can be reused
across tests and is automatically updated whenever migrations change.

- **Optimized Database Handling:**  
Previously, `dbtestutil.Open` would spin up a new container for each
test when `DB_FROM` was unset. Now, it first checks for an active
PostgreSQL instance on `localhost:5432`. If none is found, it creates a
single container that remains available for subsequent tests,
eliminating repeated container startups.

These changes address the long individual test times (10+ seconds)
reported by some users, likely due to the time Docker took to start and
complete migrations.
This commit is contained in:
Hugo Dutka
2024-11-04 17:23:31 +01:00
committed by GitHub
parent 1c29944862
commit 1bfa7d42e8
15 changed files with 641 additions and 156 deletions
+7 -8
View File
@@ -95,21 +95,17 @@ func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) {
opt(&o)
}
db := dbmem.New()
ps := pubsub.NewInMemory()
var db database.Store
var ps pubsub.Pubsub
if WillUsePostgres() {
connectionURL := os.Getenv("CODER_PG_CONNECTION_URL")
if connectionURL == "" && o.url != "" {
connectionURL = o.url
}
if connectionURL == "" {
var (
err error
closePg func()
)
connectionURL, closePg, err = Open()
var err error
connectionURL, err = Open(t)
require.NoError(t, err)
t.Cleanup(closePg)
}
if o.fixedTimezone == "" {
@@ -143,6 +139,9 @@ func NewDB(t testing.TB, opts ...Option) (database.Store, pubsub.Pubsub) {
t.Cleanup(func() {
_ = ps.Close()
})
} else {
db = dbmem.New()
ps = pubsub.NewInMemory()
}
return db, ps