80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
|
|
package test
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"fmt"
|
||
|
|
"testing"
|
||
|
|
|
||
|
|
"github.com/docker/go-connections/nat"
|
||
|
|
"github.com/testcontainers/testcontainers-go"
|
||
|
|
"google.golang.org/grpc"
|
||
|
|
"google.golang.org/grpc/credentials/insecure"
|
||
|
|
)
|
||
|
|
|
||
|
|
type APIContainerConfig struct {
|
||
|
|
ServiceName string
|
||
|
|
DB *ExternalDatabase
|
||
|
|
Network *testcontainers.DockerNetwork
|
||
|
|
}
|
||
|
|
|
||
|
|
func CreateAPIContainer(t *testing.T, ctx context.Context, config *APIContainerConfig) (*grpc.ClientConn, func()) {
|
||
|
|
port, err := nat.NewPort("tcp", "8080")
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("Failed to create port: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
container, cleanup := createContainer(t, ctx, &containerConfig{
|
||
|
|
DB: config.DB,
|
||
|
|
ServiceName: config.ServiceName,
|
||
|
|
Network: config.Network,
|
||
|
|
ExposedPorts: []nat.Port{port},
|
||
|
|
WaitForMsg: "Listening on port 8080",
|
||
|
|
})
|
||
|
|
|
||
|
|
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)
|
||
|
|
}
|
||
|
|
|
||
|
|
conn, err := grpc.NewClient(
|
||
|
|
fmt.Sprintf("%s:%s", host, mappedPort.Port()),
|
||
|
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||
|
|
)
|
||
|
|
if err != nil {
|
||
|
|
t.Fatalf("Failed to connect to gRPC server: %v", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
return conn, func() {
|
||
|
|
err = conn.Close()
|
||
|
|
if err != nil {
|
||
|
|
t.Error(err)
|
||
|
|
}
|
||
|
|
|
||
|
|
cleanup()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func CreateAPIWithDependencies(t *testing.T, ctx context.Context, serviceName string) (*grpc.ClientConn, func()) {
|
||
|
|
network, ncleanup := CreateNetwork(t, ctx)
|
||
|
|
|
||
|
|
dbconfig, dbcleanup := CreateDB(t, ctx, &CreateDatabaseConfig{
|
||
|
|
Network: network,
|
||
|
|
})
|
||
|
|
|
||
|
|
conn, ccleanup := CreateAPIContainer(t, ctx, &APIContainerConfig{
|
||
|
|
ServiceName: serviceName,
|
||
|
|
DB: dbconfig.External,
|
||
|
|
Network: network,
|
||
|
|
})
|
||
|
|
|
||
|
|
return conn, func() {
|
||
|
|
ncleanup()
|
||
|
|
dbcleanup()
|
||
|
|
ccleanup()
|
||
|
|
}
|
||
|
|
}
|