Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package postgres
- import (
- "context"
- "fmt"
- "log"
- "os"
- "testing"
- "github.com/docker/go-connections/nat"
- "github.com/testcontainers/testcontainers-go"
- "github.com/testcontainers/testcontainers-go/wait"
- )
- func createTestContainer(ctx context.Context, dbname string) (testcontainers.Container, error) {
- var port = "5432/tcp"
- // dbURL := func(port nat.Port) string {
- // return fmt.Sprintf("postgres://postgres:password@localhost:%s/%s?sslmode=disable", port.Port(), dbname)
- // }
- req := testcontainers.ContainerRequest{
- Image: "postgres:11.7",
- ExposedPorts: []string{port},
- BindMounts: map[string]string{"/home/user/Projects/typer-site/seedTestDB.psql": "/docker-entrypoint-initdb.d/init.sql"},
- Env: map[string]string{
- "POSTGRES_PASSWORD": "password",
- "POSTGRES_USER": "postgres",
- "POSTGRES_DB": dbname,
- },
- WaitingFor: wait.ForListeningPort("5432/tcp"),
- }
- container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
- ContainerRequest: req,
- Started: true,
- })
- if err != nil {
- return container, fmt.Errorf("failed to start container: %s", err.Error())
- }
- mappedPort, err := container.MappedPort(ctx, nat.Port(port))
- if err != nil {
- return container, fmt.Errorf("failed to get container external port: %s", err.Error())
- }
- log.Println("postgres container ready and running at " + mappedPort)
- // url := fmt.Sprintf("postgres://postgres:password@localhost:%s/%s?sslmode=disable", mappedPort.Port(), dbname)
- err = Connect("localhost", mappedPort.Port(), "postgres", "password", dbname)
- if err != nil {
- return container, fmt.Errorf("unable to connect to the database container: %s", err.Error())
- }
- return container, nil
- }
- func TestGetCustomTypeCount(t *testing.T) {
- mountFrom := "/home/user/Projects/typer-site/seedTestDB.psql"
- mountTo := "/docker-entrypoint-initdb.d/init.sql"
- ctx := context.Background()
- req := testcontainers.ContainerRequest{
- Image: "postgres:11.7",
- ExposedPorts: []string{"5432/tcp"},
- BindMounts: map[string]string{mountFrom: mountTo},
- Env: map[string]string{
- "POSTGRES_DB": os.Getenv("DB_NAME"),
- },
- WaitingFor: wait.ForLog("database system is ready to accept connections"),
- }
- postgresC, err := testcontainers.GenericContainer(ctx,
- testcontainers.GenericContainerRequest{
- ContainerRequest: req,
- Started: true,
- })
- if err != nil {
- panic(err)
- }
- defer postgresC.Terminate(ctx)
- p, _ := postgresC.MappedPort(ctx, "5432")
- os.Setenv("DB_PORT", p.Port())
- Connect("localhost", p.Port(), "postgres", "", os.Getenv("DB_NAME"))
- }
Advertisement
Add Comment
Please, Sign In to add comment