github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/engine/client/image_load_test.go (about) 1 package client // import "github.com/docker/docker/client" 2 3 import ( 4 "bytes" 5 "context" 6 "fmt" 7 "io" 8 "net/http" 9 "strings" 10 "testing" 11 12 "github.com/docker/docker/errdefs" 13 ) 14 15 func TestImageLoadError(t *testing.T) { 16 client := &Client{ 17 client: newMockClient(errorMock(http.StatusInternalServerError, "Server error")), 18 } 19 20 _, err := client.ImageLoad(context.Background(), nil, true) 21 if !errdefs.IsSystem(err) { 22 t.Fatalf("expected a Server Error, got %[1]T: %[1]v", err) 23 } 24 } 25 26 func TestImageLoad(t *testing.T) { 27 expectedURL := "/images/load" 28 expectedInput := "inputBody" 29 expectedOutput := "outputBody" 30 loadCases := []struct { 31 quiet bool 32 responseContentType string 33 expectedResponseJSON bool 34 expectedQueryParams map[string]string 35 }{ 36 { 37 quiet: false, 38 responseContentType: "text/plain", 39 expectedResponseJSON: false, 40 expectedQueryParams: map[string]string{ 41 "quiet": "0", 42 }, 43 }, 44 { 45 quiet: true, 46 responseContentType: "application/json", 47 expectedResponseJSON: true, 48 expectedQueryParams: map[string]string{ 49 "quiet": "1", 50 }, 51 }, 52 } 53 for _, loadCase := range loadCases { 54 client := &Client{ 55 client: newMockClient(func(req *http.Request) (*http.Response, error) { 56 if !strings.HasPrefix(req.URL.Path, expectedURL) { 57 return nil, fmt.Errorf("Expected URL '%s', got '%s'", expectedURL, req.URL) 58 } 59 contentType := req.Header.Get("Content-Type") 60 if contentType != "application/x-tar" { 61 return nil, fmt.Errorf("content-type not set in URL headers properly. Expected 'application/x-tar', got %s", contentType) 62 } 63 query := req.URL.Query() 64 for key, expected := range loadCase.expectedQueryParams { 65 actual := query.Get(key) 66 if actual != expected { 67 return nil, fmt.Errorf("%s not set in URL query properly. Expected '%s', got %s", key, expected, actual) 68 } 69 } 70 headers := http.Header{} 71 headers.Add("Content-Type", loadCase.responseContentType) 72 return &http.Response{ 73 StatusCode: http.StatusOK, 74 Body: io.NopCloser(bytes.NewReader([]byte(expectedOutput))), 75 Header: headers, 76 }, nil 77 }), 78 } 79 80 input := bytes.NewReader([]byte(expectedInput)) 81 imageLoadResponse, err := client.ImageLoad(context.Background(), input, loadCase.quiet) 82 if err != nil { 83 t.Fatal(err) 84 } 85 if imageLoadResponse.JSON != loadCase.expectedResponseJSON { 86 t.Fatalf("expected a JSON response, was not.") 87 } 88 body, err := io.ReadAll(imageLoadResponse.Body) 89 if err != nil { 90 t.Fatal(err) 91 } 92 if string(body) != expectedOutput { 93 t.Fatalf("expected %s, got %s", expectedOutput, string(body)) 94 } 95 } 96 }