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