Files
query-orchestration/internal/database/connection_test.go
T
Michael McGuinness 0ebb8a21a1 Merged in bugfix/cleanup (pull request #10)
Clean Up Testing and Linting

* somescriptcleanup

* mostgolangci

* deplatest

* imageversions

* usingscratch

* movedqueuefrtesting

* finishedunittesting

* linting

* taskfilecontext
2025-01-10 11:12:03 +00:00

120 lines
2.5 KiB
Go

package database_test
import (
"context"
"fmt"
"queryorchestration/internal/database"
"testing"
"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestDBConn(t *testing.T) {
ctx := context.Background()
_, cleanup := createDB(t, ctx)
defer cleanup()
conn := database.GetDBConn(ctx)
assert.NotNil(t, conn)
}
func TestDBConnNoDB(t *testing.T) {
ctx := context.Background()
t.Setenv("DB_USER", "user")
t.Setenv("DB_PASS", "pass")
t.Setenv("DB_HOST", "host")
t.Setenv("DB_PORT", "5432")
t.Setenv("DB_NAME", "name")
assert.Panics(t, func() { database.GetDBConn(ctx) })
}
func TestDBPool(t *testing.T) {
ctx := context.Background()
_, cleanup := createDB(t, ctx)
defer cleanup()
pool := database.GetDBPool(ctx)
assert.NotNil(t, pool)
}
type dbConfig struct {
Name string
Host string
Port int
User string
Password string
}
type db struct {
config *dbConfig
container *testcontainers.Container
}
func createDB(t *testing.T, ctx context.Context) (*db, func()) {
alias := "postgres"
port, err := nat.NewPort("tcp", "5432")
if err != nil {
t.Fatalf("Failed to create port: %v", err)
}
config := dbConfig{
Name: "queryorchestration",
Password: "pass",
User: "postgres",
Port: port.Int(),
Host: alias,
}
req := testcontainers.ContainerRequest{
Image: "postgres:17.2-alpine3.21",
Env: map[string]string{
"POSTGRES_DB": config.Name,
"POSTGRES_USER": config.User,
"POSTGRES_PASSWORD": config.Password,
},
ExposedPorts: []string{port.Port()},
WaitingFor: wait.ForListeningPort(port),
}
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
t.Fatalf("Failed to start container: %v", err)
}
mappedHost, err := container.Host(ctx)
if err != nil {
t.Fatalf("Failed to map host: %v", err)
}
mappedPort, err := container.MappedPort(ctx, port)
if err != nil {
t.Fatalf("Failed to map port: %v", err)
}
config.Host = mappedHost
config.Port = mappedPort.Int()
t.Setenv("DB_USER", config.User)
t.Setenv("DB_PASS", config.Password)
t.Setenv("DB_HOST", config.Host)
t.Setenv("DB_PORT", fmt.Sprint(config.Port))
t.Setenv("DB_NAME", config.Name)
return &db{
config: &config,
container: &container,
}, func() {
err := container.Terminate(ctx)
if err != nil {
t.Error(err)
}
}
}