container.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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.CreateResponse, 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. t.Helper()
  45. c, err := create(ctx, t, client, ops...)
  46. assert.NilError(t, err)
  47. return c.ID
  48. }
  49. // CreateExpectingErr creates a container, expecting an error with the specified message
  50. func CreateExpectingErr(ctx context.Context, t *testing.T, client client.APIClient, errMsg string, ops ...func(*TestContainerConfig)) {
  51. _, err := create(ctx, t, client, ops...)
  52. assert.ErrorContains(t, err, errMsg)
  53. }
  54. // Run creates and start a container with the specified options
  55. func Run(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) string {
  56. t.Helper()
  57. id := Create(ctx, t, client, ops...)
  58. err := client.ContainerStart(ctx, id, types.ContainerStartOptions{})
  59. assert.NilError(t, err)
  60. return id
  61. }