container.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package container
  2. import (
  3. "context"
  4. "testing"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/api/types/container"
  7. "github.com/docker/docker/api/types/network"
  8. "github.com/docker/docker/client"
  9. "gotest.tools/assert"
  10. )
  11. // TestContainerConfig holds container configuration struct that
  12. // are used in api calls.
  13. type TestContainerConfig struct {
  14. Name string
  15. Config *container.Config
  16. HostConfig *container.HostConfig
  17. NetworkingConfig *network.NetworkingConfig
  18. }
  19. // create creates a container with the specified options
  20. func create(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) (container.ContainerCreateCreatedBody, error) {
  21. t.Helper()
  22. config := &TestContainerConfig{
  23. Config: &container.Config{
  24. Image: "busybox",
  25. Cmd: []string{"top"},
  26. },
  27. HostConfig: &container.HostConfig{},
  28. NetworkingConfig: &network.NetworkingConfig{},
  29. }
  30. for _, op := range ops {
  31. op(config)
  32. }
  33. return client.ContainerCreate(ctx, config.Config, config.HostConfig, config.NetworkingConfig, config.Name)
  34. }
  35. // Create creates a container with the specified options, asserting that there was no error
  36. func Create(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) string {
  37. c, err := create(ctx, t, client, ops...)
  38. assert.NilError(t, err)
  39. return c.ID
  40. }
  41. // CreateExpectingErr creates a container, expecting an error with the specified message
  42. func CreateExpectingErr(ctx context.Context, t *testing.T, client client.APIClient, errMsg string, ops ...func(*TestContainerConfig)) {
  43. _, err := create(ctx, t, client, ops...)
  44. assert.ErrorContains(t, err, errMsg)
  45. }
  46. // Run creates and start a container with the specified options
  47. // nolint: golint
  48. func Run(t *testing.T, ctx context.Context, client client.APIClient, ops ...func(*TestContainerConfig)) string { // nolint: golint
  49. t.Helper()
  50. id := Create(ctx, t, client, ops...)
  51. err := client.ContainerStart(ctx, id, types.ContainerStartOptions{})
  52. assert.NilError(t, err)
  53. return id
  54. }