|
| 1 | +package helpers |
| 2 | + |
| 3 | +import ( |
| 4 | + "io/ioutil" |
| 5 | + "net" |
| 6 | + "net/url" |
| 7 | + "strconv" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/docker/go-connections/nat" |
| 11 | + "github.com/mattn/go-shellwords" |
| 12 | + "github.com/stretchr/testify/require" |
| 13 | + "github.com/testcontainers/testcontainers-go" |
| 14 | + tcexec "github.com/testcontainers/testcontainers-go/exec" |
| 15 | + "github.com/testcontainers/testcontainers-go/wait" |
| 16 | +) |
| 17 | + |
| 18 | +func ContExecNoOutput(tb testing.TB, container *testcontainers.DockerContainer, cmd string, options ...tcexec.ProcessOption) { |
| 19 | + tb.Helper() |
| 20 | + ctx := tb.Context() |
| 21 | + |
| 22 | + args, err := shellwords.Parse(cmd) |
| 23 | + require.NoError(tb, err) |
| 24 | + |
| 25 | + c, output, err := container.Exec(ctx, args, options...) |
| 26 | + require.NoError(tb, err) |
| 27 | + outbytes, _ := ioutil.ReadAll(output) |
| 28 | + require.Zero(tb, c, string(outbytes)) |
| 29 | +} |
| 30 | + |
| 31 | +type tLogger struct { |
| 32 | + tb testing.TB |
| 33 | +} |
| 34 | + |
| 35 | +func (l tLogger) Printf(format string, v ...any) { |
| 36 | + l.tb.Logf(format, v...) |
| 37 | +} |
| 38 | + |
| 39 | +func RunContainer(tb testing.TB, image string, port int, opts ...testcontainers.ContainerCustomizer) (c *testcontainers.DockerContainer, addr string) { |
| 40 | + tb.Helper() |
| 41 | + ctx := tb.Context() |
| 42 | + |
| 43 | + portStr := strconv.Itoa(port) + "/tcp" |
| 44 | + |
| 45 | + opts = append(opts, |
| 46 | + testcontainers.WithExposedPorts(portStr), |
| 47 | + testcontainers.WithLogger(tLogger{tb}), |
| 48 | + testcontainers.WithAdditionalWaitStrategy( |
| 49 | + wait.ForListeningPort(nat.Port(portStr)), |
| 50 | + ), |
| 51 | + ) |
| 52 | + |
| 53 | + c, err := testcontainers.Run(ctx, image, opts...) |
| 54 | + testcontainers.CleanupContainer(tb, c) |
| 55 | + require.NoError(tb, err) |
| 56 | + |
| 57 | + mappedPort, err := c.MappedPort(ctx, nat.Port(portStr)) |
| 58 | + require.NoError(tb, err) |
| 59 | + mappedIp, err := c.Host(ctx) |
| 60 | + require.NoError(tb, err) |
| 61 | + |
| 62 | + mappedAddr := (&url.URL{ |
| 63 | + Scheme: "http", |
| 64 | + Host: net.JoinHostPort(mappedIp, mappedPort.Port()), |
| 65 | + }).String() |
| 66 | + |
| 67 | + return c, mappedAddr |
| 68 | +} |
0 commit comments