container.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // nolint: golint
  21. func create(t *testing.T, ctx context.Context, client client.APIClient, ops ...func(*TestContainerConfig)) (container.ContainerCreateCreatedBody, error) { // nolint: golint
  22. t.Helper()
  23. config := &TestContainerConfig{
  24. Config: &container.Config{
  25. Image: "busybox",
  26. Cmd: []string{"top"},
  27. },
  28. HostConfig: &container.HostConfig{},
  29. NetworkingConfig: &network.NetworkingConfig{},
  30. }
  31. for _, op := range ops {
  32. op(config)
  33. }
  34. return client.ContainerCreate(ctx, config.Config, config.HostConfig, config.NetworkingConfig, config.Name)
  35. }
  36. // Create creates a container with the specified options, asserting that there was no error
  37. func Create(t *testing.T, ctx context.Context, client client.APIClient, ops ...func(*TestContainerConfig)) string { // nolint: golint
  38. c, err := create(t, ctx, client, ops...)
  39. assert.NilError(t, err)
  40. return c.ID
  41. }
  42. // CreateExpectingErr creates a container, expecting an error with the specified message
  43. func CreateExpectingErr(t *testing.T, ctx context.Context, client client.APIClient, errMsg string, ops ...func(*TestContainerConfig)) { // nolint: golint
  44. _, err := create(t, ctx, client, ops...)
  45. assert.ErrorContains(t, err, errMsg)
  46. }
  47. // Run creates and start a container with the specified options
  48. // nolint: golint
  49. func Run(t *testing.T, ctx context.Context, client client.APIClient, ops ...func(*TestContainerConfig)) string { // nolint: golint
  50. t.Helper()
  51. id := Create(t, ctx, client, ops...)
  52. err := client.ContainerStart(ctx, id, types.ContainerStartOptions{})
  53. assert.NilError(t, err)
  54. return id
  55. }