0ebb8a21a1
Clean Up Testing and Linting * somescriptcleanup * mostgolangci * deplatest * imageversions * usingscratch * movedqueuefrtesting * finishedunittesting * linting * taskfilecontext
83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
package repository_test
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"queryorchestration/internal/database"
|
|
"testing"
|
|
|
|
"github.com/docker/go-connections/nat"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/testcontainers/testcontainers-go"
|
|
"github.com/testcontainers/testcontainers-go/wait"
|
|
)
|
|
|
|
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")
|
|
|
|
database.RunMigrations(&database.MigrationConfig{
|
|
BasePath: path.Join(os.Getenv("PWD"), "../../.."),
|
|
})
|
|
|
|
pool := database.GetDBPool(ctx)
|
|
|
|
return &db{
|
|
pool: pool,
|
|
container: &container,
|
|
}, func() {
|
|
err := container.Terminate(ctx)
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
}
|
|
}
|