testcontainers
This commit is contained in:
82
internal/todo/repository/postgres/postgres_test.go
Normal file
82
internal/todo/repository/postgres/postgres_test.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"log"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.michaelthomson.dev/mthomson/habits/internal/migrate"
|
||||
"gitea.michaelthomson.dev/mthomson/habits/internal/todo/repository"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
)
|
||||
|
||||
type TestDatabase struct {
|
||||
Db *sql.DB
|
||||
container testcontainers.Container
|
||||
}
|
||||
|
||||
|
||||
func NewTestDatabase() *TestDatabase {
|
||||
ctx := context.Background()
|
||||
// create container
|
||||
postgresContainer, err := postgres.Run(ctx,
|
||||
"postgres:16-alpine",
|
||||
postgres.WithDatabase("todo"),
|
||||
postgres.WithUsername("todo"),
|
||||
postgres.WithPassword("password"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(5*time.Second)),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create postgres container, %v\n", err)
|
||||
}
|
||||
|
||||
connectionString, err := postgresContainer.ConnectionString(ctx)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to get connection string")
|
||||
}
|
||||
|
||||
// create db pool
|
||||
db, err := sql.Open("pgx", connectionString)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to open db pool")
|
||||
}
|
||||
|
||||
migrate.Migrate(db)
|
||||
|
||||
return &TestDatabase{
|
||||
Db: db,
|
||||
container: postgresContainer,
|
||||
}
|
||||
}
|
||||
|
||||
func (tdb *TestDatabase) TearDown() {
|
||||
tdb.Db.Close()
|
||||
_ = tdb.container.Terminate(context.Background())
|
||||
}
|
||||
|
||||
func TestCreate(t *testing.T) {
|
||||
tdb := NewTestDatabase()
|
||||
defer tdb.TearDown()
|
||||
r := NewPostgresTodoRepository(tdb.Db)
|
||||
|
||||
todo := repository.TodoRow{Name: "clean dishes", Done: false}
|
||||
|
||||
newTodo, err := r.Create(todo)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Expected no error, got %v", err)
|
||||
}
|
||||
|
||||
if newTodo.Id != 1 || newTodo.Name != todo.Name || newTodo.Done != todo.Done {
|
||||
t.Errorf("got %+v, want %+v", newTodo, todo)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user