github.com/rish1988/moby@v25.0.2+incompatible/internal/testutils/specialimage/load.go (about)

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