build.go 1.3 KB

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