github.com/toplink-cn/moby@v0.0.0-20240305205811-460b4aebdf81/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 "gotest.tools/v3/assert" 16 ) 17 18 type SpecialImageFunc func(string) error 19 20 func Load(ctx context.Context, t *testing.T, apiClient client.APIClient, imageFunc SpecialImageFunc) string { 21 tempDir := t.TempDir() 22 23 err := imageFunc(tempDir) 24 assert.NilError(t, err) 25 26 rc, err := archive.TarWithOptions(tempDir, &archive.TarOptions{}) 27 assert.NilError(t, err) 28 29 defer rc.Close() 30 31 resp, err := apiClient.ImageLoad(ctx, rc, true) 32 assert.NilError(t, err, "Failed to load dangling image") 33 34 defer resp.Body.Close() 35 36 if !assert.Check(t, err) { 37 respBody, err := io.ReadAll(resp.Body) 38 if err != nil { 39 t.Fatalf("Failed to read response body: %v", err) 40 return "" 41 } 42 t.Fatalf("Failed load: %s", string(respBody)) 43 } 44 45 all, err := io.ReadAll(resp.Body) 46 assert.NilError(t, err) 47 48 decoder := json.NewDecoder(bytes.NewReader(all)) 49 for { 50 var msg jsonmessage.JSONMessage 51 err := decoder.Decode(&msg) 52 if errors.Is(err, io.EOF) { 53 break 54 } else { 55 assert.NilError(t, err) 56 } 57 58 msg.Stream = strings.TrimSpace(msg.Stream) 59 60 if _, imageID, hasID := strings.Cut(msg.Stream, "Loaded image ID: "); hasID { 61 return imageID 62 } 63 if _, imageRef, hasRef := strings.Cut(msg.Stream, "Loaded image: "); hasRef { 64 return imageRef 65 } 66 } 67 68 t.Fatalf("failed to read image ID\n%s", string(all)) 69 return "" 70 }