103 lines
2.3 KiB
Go
103 lines
2.3 KiB
Go
package database_test
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"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()
|
|
_, container := createDB(t, ctx)
|
|
defer container.Terminate(ctx)
|
|
|
|
conn := database.GetDBConn(ctx)
|
|
assert.NotNil(t, conn)
|
|
|
|
os.Setenv("DB_HOST", "")
|
|
assert.Panics(t, func() { database.GetDBConn(ctx) })
|
|
}
|
|
|
|
func TestDBPool(t *testing.T) {
|
|
ctx := context.Background()
|
|
_, container := createDB(t, ctx)
|
|
defer container.Terminate(ctx)
|
|
|
|
pool := database.GetDBPool(ctx)
|
|
assert.NotNil(t, pool)
|
|
|
|
os.Setenv("DB_HOST", "")
|
|
assert.Panics(t, func() { database.GetDBPool(ctx) })
|
|
}
|
|
|
|
type dbConfig struct {
|
|
Name string
|
|
Host string
|
|
Port int
|
|
User string
|
|
Password string
|
|
}
|
|
|
|
func createDB(t *testing.T, ctx context.Context) (*dbConfig, testcontainers.Container) {
|
|
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:latest",
|
|
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()
|
|
|
|
os.Setenv("DB_USER", config.User)
|
|
os.Setenv("DB_PASS", config.Password)
|
|
os.Setenv("DB_HOST", config.Host)
|
|
os.Setenv("DB_PORT", fmt.Sprint(config.Port))
|
|
os.Setenv("DB_NAME", config.Name)
|
|
|
|
return &config, container
|
|
}
|