github.com/goreleaser/goreleaser@v1.25.1/internal/testlib/docker.go (about)

     1  package testlib
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/ory/dockertest/v3"
     8  	"github.com/ory/dockertest/v3/docker"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  var (
    13  	dockerPoolOnce sync.Once
    14  	dockerPool     *dockertest.Pool
    15  )
    16  
    17  // MustDockerPool gets a single dockertet.Pool.
    18  func MustDockerPool(f Fataler) *dockertest.Pool {
    19  	dockerPoolOnce.Do(func() {
    20  		pool, err := dockertest.NewPool("")
    21  		if err != nil {
    22  			f.Fatal(err)
    23  		}
    24  		if err := pool.Client.Ping(); err != nil {
    25  			f.Fatal(err)
    26  		}
    27  		dockerPool = pool
    28  	})
    29  	return dockerPool
    30  }
    31  
    32  // MustKillContainer kills the given container by name if it exists in the
    33  // current dockertest.Pool.
    34  func MustKillContainer(f Fataler, name string) {
    35  	pool := MustDockerPool(f)
    36  	if trash, ok := pool.ContainerByName(name); ok {
    37  		if err := pool.Purge(trash); err != nil {
    38  			f.Fatal(err)
    39  		}
    40  	}
    41  }
    42  
    43  // Fataler interface, can be a log.Default() or testing.TB, for example.
    44  type Fataler interface {
    45  	Fatal(args ...any)
    46  }
    47  
    48  // StartRegistry starts a registry with the given name in the given port, and
    49  // sets up its deletion on test.Cleanup.
    50  func StartRegistry(tb testing.TB, name, port string) {
    51  	tb.Helper()
    52  
    53  	pool := MustDockerPool(tb)
    54  	MustKillContainer(tb, name)
    55  	resource, err := pool.RunWithOptions(&dockertest.RunOptions{
    56  		Name:       name,
    57  		Repository: "registry",
    58  		Tag:        "2",
    59  		PortBindings: map[docker.Port][]docker.PortBinding{
    60  			docker.Port("5000/tcp"): {{HostPort: port}},
    61  		},
    62  	}, func(hc *docker.HostConfig) {
    63  		hc.AutoRemove = true
    64  	})
    65  	require.NoError(tb, err)
    66  
    67  	tb.Cleanup(func() {
    68  		require.NoError(tb, pool.Purge(resource))
    69  	})
    70  }