github.com/moby/docker@v26.1.3+incompatible/internal/testutils/specialimage/load.go (about)

     1  package specialimage
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/json"
     7  	"errors"
     8  	"io"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/docker/docker/client"
    13  	"github.com/docker/docker/pkg/archive"
    14  	"github.com/docker/docker/pkg/jsonmessage"
    15  	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
    16  	"gotest.tools/v3/assert"
    17  )
    18  
    19  type SpecialImageFunc func(string) (*ocispec.Index, error)
    20  
    21  func Load(ctx context.Context, t *testing.T, apiClient client.APIClient, imageFunc SpecialImageFunc) string {
    22  	tempDir := t.TempDir()
    23  
    24  	_, err := imageFunc(tempDir)
    25  	assert.NilError(t, err)
    26  
    27  	rc, err := archive.TarWithOptions(tempDir, &archive.TarOptions{})
    28  	assert.NilError(t, err)
    29  
    30  	defer rc.Close()
    31  
    32  	resp, err := apiClient.ImageLoad(ctx, rc, true)
    33  	assert.NilError(t, err, "Failed to load dangling image")
    34  
    35  	defer resp.Body.Close()
    36  
    37  	if !assert.Check(t, err) {
    38  		respBody, err := io.ReadAll(resp.Body)
    39  		if err != nil {
    40  			t.Fatalf("Failed to read response body: %v", err)
    41  			return ""
    42  		}
    43  		t.Fatalf("Failed load: %s", string(respBody))
    44  	}
    45  
    46  	all, err := io.ReadAll(resp.Body)
    47  	assert.NilError(t, err)
    48  
    49  	decoder := json.NewDecoder(bytes.NewReader(all))
    50  	for {
    51  		var msg jsonmessage.JSONMessage
    52  		err := decoder.Decode(&msg)
    53  		if errors.Is(err, io.EOF) {
    54  			break
    55  		} else {
    56  			assert.NilError(t, err)
    57  		}
    58  
    59  		msg.Stream = strings.TrimSpace(msg.Stream)
    60  
    61  		if _, imageID, hasID := strings.Cut(msg.Stream, "Loaded image ID: "); hasID {
    62  			return imageID
    63  		}
    64  		if _, imageRef, hasRef := strings.Cut(msg.Stream, "Loaded image: "); hasRef {
    65  			return imageRef
    66  		}
    67  	}
    68  
    69  	t.Fatalf("failed to read image ID\n%s", string(all))
    70  	return ""
    71  }