build.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package build
  2. import (
  3. "context"
  4. "encoding/json"
  5. "io"
  6. "testing"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/client"
  9. "github.com/docker/docker/pkg/jsonmessage"
  10. "github.com/docker/docker/testutil/fakecontext"
  11. "gotest.tools/v3/assert"
  12. )
  13. // Do builds an image from the given context and returns the image ID.
  14. func Do(ctx context.Context, t *testing.T, client client.APIClient, buildCtx *fakecontext.Fake) string {
  15. resp, err := client.ImageBuild(ctx, buildCtx.AsTarReader(t), types.ImageBuildOptions{})
  16. if resp.Body != nil {
  17. defer resp.Body.Close()
  18. }
  19. assert.NilError(t, err)
  20. img := GetImageIDFromBody(t, resp.Body)
  21. t.Cleanup(func() {
  22. client.ImageRemove(ctx, img, types.ImageRemoveOptions{Force: true})
  23. })
  24. return img
  25. }
  26. // GetImageIDFromBody reads the image ID from the build response body.
  27. func GetImageIDFromBody(t *testing.T, body io.Reader) string {
  28. var (
  29. jm jsonmessage.JSONMessage
  30. br types.BuildResult
  31. dec = json.NewDecoder(body)
  32. )
  33. for {
  34. err := dec.Decode(&jm)
  35. if err == io.EOF {
  36. break
  37. }
  38. assert.NilError(t, err)
  39. if jm.Aux == nil {
  40. continue
  41. }
  42. assert.NilError(t, json.Unmarshal(*jm.Aux, &br))
  43. assert.Assert(t, br.ID != "", "could not read image ID from build output")
  44. break
  45. }
  46. io.Copy(io.Discard, body)
  47. return br.ID
  48. }