Last active
June 6, 2023 19:11
-
-
Save peterldowns/c35fdc23532056b0897b7aefea9417e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
version: "3.6" | |
services: | |
testdb: | |
image: postgres:15 | |
environment: | |
POSTGRES_PASSWORD: password | |
restart: unless-stopped | |
volumes: | |
# Uses a tmpfs volume to make tests extremely fast. The data in test | |
# databases is not persisted across restarts, nor does it need to be. | |
- type: tmpfs | |
target: /var/lib/postgresql/data/ | |
command: | |
- "postgres" | |
- "-c" | |
- "fsync=off" | |
- "-c" | |
- "shared_buffers=1024MB" | |
- "-c" | |
- "synchronous_commit=off" | |
- "-c" | |
- "full_page_writes=off" | |
- "-c" | |
- "log_statement=all" | |
- "-c" | |
- "max_connections=1000" | |
ports: | |
- "5433:5432" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main_test | |
import ( | |
"testing" | |
"database/sql" | |
_ "github.com/lib/pq" // or any other postgres driver | |
"github.com/peterldowns/testy/assert" | |
"github.com/peterldowns/pgtestdb" | |
"github.com/peterldowns/pgtestdb/migrators/goosemigrator" | |
) | |
// runs against its own, fast, isolated, postgres database | |
// parallel works great :) | |
func TestWithDatabase(t *testing.T) { | |
t.Parallel() | |
db := newDB(t) | |
var message string | |
err := db.QueryRow("select 'hello world'").Scan(&message) | |
assert.Nil(t, err) | |
assert.Equal(t, "hello world", message) | |
} | |
// creates a new database or fails the test. | |
func newDB(t *testing.T) *sql.DB { | |
t.Helper() | |
migrator := goosemigrator.New("migrations") | |
return pgtestdb.New(t, pgtestdb.Config{ | |
DriverName: "postgres", | |
Host: "localhost", | |
User: "postgres", | |
Password: "password", | |
Port: "5433", | |
Options: "sslmode=disable", | |
}, migrator) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example of how to use peterldowns/pgtestdb to run a test that gets its own test database, fully migrated with pressly/goose.
Save these two files to a directory, then:
If you want to actually run some migrations, create a folder
migrations
and add a migration file, like0001_cats.sql
. This example uses pressly/goose but there are plenty of other adaptors for the most common migration frameworks: