container.go 2.2 KB

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