health_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package container
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  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/api/types/strslice"
  10. "github.com/docker/docker/client"
  11. "github.com/docker/docker/integration/util/request"
  12. "github.com/gotestyourself/gotestyourself/poll"
  13. "github.com/stretchr/testify/require"
  14. )
  15. // TestHealthCheckWorkdir verifies that health-checks inherit the containers'
  16. // working-dir.
  17. func TestHealthCheckWorkdir(t *testing.T) {
  18. defer setupTest(t)()
  19. ctx := context.Background()
  20. client := request.NewAPIClient(t)
  21. c, err := client.ContainerCreate(ctx,
  22. &container.Config{
  23. Image: "busybox",
  24. Tty: true,
  25. WorkingDir: "/foo",
  26. Cmd: strslice.StrSlice([]string{"top"}),
  27. Healthcheck: &container.HealthConfig{
  28. Test: []string{"CMD-SHELL", "if [ \"$PWD\" = \"/foo\" ]; then exit 0; else exit 1; fi;"},
  29. Interval: 50 * time.Millisecond,
  30. Retries: 3,
  31. },
  32. },
  33. &container.HostConfig{},
  34. &network.NetworkingConfig{},
  35. "healthtest",
  36. )
  37. require.NoError(t, err)
  38. err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{})
  39. require.NoError(t, err)
  40. poll.WaitOn(t, pollForHealthStatus(ctx, client, c.ID, types.Healthy), poll.WithDelay(100*time.Millisecond))
  41. }
  42. func pollForHealthStatus(ctx context.Context, client client.APIClient, containerID string, healthStatus string) func(log poll.LogT) poll.Result {
  43. return func(log poll.LogT) poll.Result {
  44. inspect, err := client.ContainerInspect(ctx, containerID)
  45. switch {
  46. case err != nil:
  47. return poll.Error(err)
  48. case inspect.State.Health.Status == healthStatus:
  49. return poll.Success()
  50. default:
  51. return poll.Continue("waiting for container to become %s", healthStatus)
  52. }
  53. }
  54. }