93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
|
|
package server_test
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"fmt"
|
||
|
|
"queryorchestration/internal/database"
|
||
|
|
"queryorchestration/internal/server"
|
||
|
|
"testing"
|
||
|
|
|
||
|
|
"github.com/docker/go-connections/nat"
|
||
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
||
|
|
"github.com/stretchr/testify/assert"
|
||
|
|
"github.com/testcontainers/testcontainers-go"
|
||
|
|
"github.com/testcontainers/testcontainers-go/wait"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestNew(t *testing.T) {
|
||
|
|
ctx := context.Background()
|
||
|
|
|
||
|
|
_, cleanup := createDB(t, ctx)
|
||
|
|
defer cleanup()
|
||
|
|
|
||
|
|
newCfg := &server.NewConfig{
|
||
|
|
BasePath: "../..",
|
||
|
|
}
|
||
|
|
|
||
|
|
cfg := server.New(ctx, newCfg)
|
||
|
|
assert.NotNil(t, cfg)
|
||
|
|
}
|
||
|
|
|
||
|
|
type db struct {
|
||
|
|
pool *pgxpool.Pool
|
||
|
|
container *testcontainers.Container
|
||
|
|
}
|
||
|
|
|
||
|
|
func createDB(t *testing.T, ctx context.Context) (*db, func()) {
|
||
|
|
port, err := nat.NewPort("tcp", "5432")
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("Failed to create port: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
name := "queryorchestration"
|
||
|
|
pass := "pass"
|
||
|
|
user := "postgres"
|
||
|
|
|
||
|
|
req := testcontainers.ContainerRequest{
|
||
|
|
Image: "postgres:17.2-alpine3.21",
|
||
|
|
Env: map[string]string{
|
||
|
|
"POSTGRES_DB": name,
|
||
|
|
"POSTGRES_USER": user,
|
||
|
|
"POSTGRES_PASSWORD": pass,
|
||
|
|
},
|
||
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
host, err := container.Host(ctx)
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("Failed to extract host: %v", err)
|
||
|
|
}
|
||
|
|
mappedPort, err := container.MappedPort(ctx, port)
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("Failed to extract port: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
t.Setenv("DB_USER", user)
|
||
|
|
t.Setenv("DB_PASS", pass)
|
||
|
|
t.Setenv("DB_HOST", host)
|
||
|
|
t.Setenv("DB_PORT", fmt.Sprint(mappedPort.Int()))
|
||
|
|
t.Setenv("DB_NAME", name)
|
||
|
|
t.Setenv("DB_NOSSL", "1")
|
||
|
|
|
||
|
|
pool := database.GetDBPool(ctx)
|
||
|
|
|
||
|
|
return &db{
|
||
|
|
pool: pool,
|
||
|
|
container: &container,
|
||
|
|
}, func() {
|
||
|
|
err := container.Terminate(ctx)
|
||
|
|
if err != nil {
|
||
|
|
t.Error(err)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|