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