Skip to content

Instantly share code, notes, and snippets.

@stormvirux
Forked from Eun/database.go
Created August 2, 2024 08:09
Show Gist options
  • Save stormvirux/cbeec3f0ace85717c2dd7f30fedea6fe to your computer and use it in GitHub Desktop.
Save stormvirux/cbeec3f0ace85717c2dd7f30fedea6fe to your computer and use it in GitHub Desktop.

Revisions

  1. @Eun Eun revised this gist May 5, 2021. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions database.go
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,7 @@
    // usage:
    // testDB := testhelpers.NewTestDatabase(t)
    // defer testDB.Close(t)
    // println(testDB.ConnectionString(t))
    package testhelpers

    import (
  2. @Eun Eun created this gist May 5, 2021.
    59 changes: 59 additions & 0 deletions database.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    package testhelpers

    import (
    "context"
    "fmt"
    "testing"
    "time"

    "github.com/stretchr/testify/require"

    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/wait"
    )

    type TestDatabase struct {
    instance testcontainers.Container
    }

    func NewTestDatabase(t *testing.T) *TestDatabase {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()
    req := testcontainers.ContainerRequest{
    Image: "postgres:12",
    ExposedPorts: []string{"5432/tcp"},
    AutoRemove: true,
    Env: map[string]string{
    "POSTGRES_USER": "postgres",
    "POSTGRES_PASSWORD": "postgres",
    "POSTGRES_DB": "postgres",
    },
    WaitingFor: wait.ForListeningPort("5432/tcp"),
    }
    postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
    ContainerRequest: req,
    Started: true,
    })
    require.NoError(t, err)
    return &TestDatabase{
    instance: postgres,
    }
    }

    func (db *TestDatabase) Port(t *testing.T) int {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()
    p, err := db.instance.MappedPort(ctx, "5432")
    require.NoError(t, err)
    return p.Int()
    }

    func (db *TestDatabase) ConnectionString(t *testing.T) string {
    return fmt.Sprintf("postgres://postgres:[email protected]:%d/postgres", db.Port(t))
    }

    func (db *TestDatabase) Close(t *testing.T) {
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()
    require.NoError(t, db.instance.Terminate(ctx))
    }